﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using Microsoft.Reporting.WinForms;
using LsMisCommon;
using WeifenLuo.WinFormsUI.Docking;
using System.Configuration;

namespace card
{
    public partial class STCHDJ : DockContent
    {
        public bool IsCycel = false;

        public static WebDG.Service ws = new card.WebDG.Service();
        bool is_new_card = false;
        bool is_update = false;
        string update_id = "";
        string previous_car_no = "";//previous car NO
        //following variable is used to store the previous record
        bool owner_is_selected = false;
        int owner_index = -1;
        bool shipname_is_selected = false;
        int shipname_index = -1;

        string strVersion = "1.0.0.5";

        double f_DJ = 1;//计费单价
        double f_JE_min = 5;//最小计费金额

        //定义自动刷新的delegate
        delegate void DataGridTruckLoginHandler(DataTable dt);
        event DataGridTruckLoginHandler TruckLogin;
        delegate void UncheckLabelRereshHandler(DataTable uncheck_cars);
        event UncheckLabelRereshHandler UncheckRefresh;

        public STCHDJ()
        {
            InitializeComponent();
        }

        //获取市入地址wawrdin
        static string wawrdout = ConfigurationManager.AppSettings["wawrdout"];

        static String interval = System.Configuration.ConfigurationManager.AppSettings["refresh_interval"];
        static int refresh_interval = int.Parse(interval) * 60000;
        System.Timers.Timer t = new System.Timers.Timer(refresh_interval);//实例化Timer类，设置间隔时间为60秒；

        #region==========船名下拉列表项的类定义=============
        class ListItem : System.Object
        {
            private string _ShipName = string.Empty;
            private string _CargoName = string.Empty;
            private string _StackName = string.Empty;
            private string _BillNO = string.Empty;
            private string _CargonNO = string.Empty;

            private string _CkindNO = string.Empty;
            private string _GetOwner = string.Empty;
            private string _Package = string.Empty;
            private string _ShipNO = string.Empty;

            public string CkindNO
            {
                get { return this._CkindNO; }
                set { this._CkindNO = value; }
            }
            public string GetOwner
            {
                get { return this._GetOwner; }
                set { this._GetOwner = value; }
            }
            public string Package
            {
                get { return this._Package; }
                set { this._Package = value; }
            }
            public string ShipNO
            {
                get { return this._ShipNO; }
                set { this._ShipNO = value; }
            }

            public string ShipName
            {
                get { return this._ShipName; }
                set { this._ShipName = value; }
            }

            public string CargoName
            {
                get { return this._CargoName; }
                set { this._CargoName = value; }
            }

            public string StackName
            {
                get { return this._StackName; }
                set { this._StackName = value; }
            }

            public string BillNO
            {
                get { return this._BillNO; }
                set { this._BillNO = value; }
            }

            public string CargonNO
            {
                get { return this._CargonNO; }
                set { this._CargonNO = value; }
            }

            public string DisplayName
            {
                get { return this._BillNO + "--" + this._StackName + "--" + this._ShipName + "--" + this._CargoName; }
                //set { this._CargonNO = value; }
            }

            public ListItem(string bill_no, string stack_name, string ship_name, string cargo_name, string cargo_no, string ckind_no, string get_owner, string package, string ship_no)
            {
                this._ShipName = ship_name;
                this._CargoName = cargo_name;
                this._StackName = stack_name;
                this._BillNO = bill_no;
                this._CargonNO = cargo_no;
                //private string _CkindNO = string.Empty;
                //private string _GetOwner = string.Empty;
                //private string _Package = string.Empty;
                //private string _ShipNO = string.Empty;
                this._CkindNO = ckind_no;
                this._GetOwner = get_owner;
                this._Package = package;
                this._ShipNO = ship_no;
            }
            public override string ToString()
            {
                return this._BillNO + "--" + this._StackName + "--" + this._ShipName + "--" + this._CargoName;
            }
        }
        #endregion

        #region==========流向下拉列表项的类定义=============
        class ListItem_LX : System.Object
        {
            public string TDH { get; set; }
            public string CARGONO { get; set; }
            public string CARGONAME { get; set; }
            public string STACKNAME { get; set; }
            public string SHIPNO { get; set; }
            public string SHIPNAME { get; set; }
            public string BILLNO { get; set; }
            public string SHIPPER_NAME { get; set; }
            public string GETOWNER { get; set; }

            public string DisplayName
            {
                get
                {
                    return this.TDH + "--" + this.BILLNO + "--" + this.STACKNAME + "--" + this.SHIPNAME + "--" + this.CARGONAME;
                }
            }

            public ListItem_LX(string _tdh, string _cargoNo, string _cargoName, string _stackName, string _shipNo, string _shipName, string _billNo, string _shipperName, string _getOwner)
            {
                this.TDH = _tdh;
                this.CARGONO = _cargoNo;
                this.CARGONAME = _cargoName;
                this.STACKNAME = _stackName;
                this.SHIPNO = _shipNo;
                this.SHIPNAME = _shipName;
                this.BILLNO = _billNo;
                this.SHIPPER_NAME = _shipperName;
                this.GETOWNER = _getOwner;
            }
        }
        #endregion

        string card_add = "";
        private void STCHDJ_Load(object sender, EventArgs e)
        {
            //获得发卡地点
            card_add = System.Configuration.ConfigurationSettings.AppSettings["card_address"];

            this.Text = "市提车货登记--" + card_add;

            // string dtime = DateTime.Now.ToString();
            string dtime = ws.GetSysDateTime().ToString();
            this.textBox_loginTime.Text = dtime;

            //this.comboBox_owner.DataSource = this.shippers.Tables[0];
            this.comboBox_owner.DataSource = Session.Shippers.Tables[0];
            this.comboBox_owner.ValueMember = "SHIPPER_NAME";
            //this.comboBox_owner.DisplayMember = "SHIPPER_BRIEF";//
            this.comboBox_owner.DisplayMember = "DESCRIPTION";

            //this.ucComboBox1.DataSource = Session.Shippers.Tables[0];
            //this.ucComboBox1.ValueMember = "SHIPPER_NAME";
            //this.ucComboBox1.DisplayMember = "DESCRIPTION";

            //Set the datasource for 
            this.comboBox_cargoName.DataSource = Session.Cargo_names.Tables[0];
            this.comboBox_cargoName.ValueMember = "CARGO_NAM";
            this.comboBox_cargoName.DisplayMember = "DISPLAYNAME";

            //Set the datasource for ship name combobox
            //string sql_ship_names = "select SHIPNO||'/'||SHIPNAME||'/'||CARGONAME||'/'||VOYAGE||'/'||IFTRADE as DISPLAYNAME,VOYAGE,SHIPNAME from v_ship_tcc";
            //DataSet ds_ship_name = ws.getDataSet_Serv(sql_ship_names);
            //this.comboBox_shipname.DataSource = ds_ship_name.Tables[0];
            //this.comboBox_shipname.ValueMember = "SHIPNAME";
            //this.comboBox_shipname.DisplayMember = "DISPLAYNAME";
            ////this.comboBox_shipname.SelectedIndex = -1;
            string sql_ship_names = "select SHIPNAME,CARGONAME,CARGONO,BILLNO,STACKNAME,CKINDNO,GETOWNER,PACKAGE,SHIPNO from v_ship_tcc";
            DataSet ds_ship_name = ws.getDataSet_Serv(sql_ship_names);
            DataTable dt = ds_ship_name.Tables[0];

            List<ListItem> items2 = new List<ListItem>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string billNo = dt.Rows[i]["BILLNO"].ToString();
                string stackName = dt.Rows[i]["STACKNAME"].ToString();
                string shipName = dt.Rows[i]["SHIPNAME"].ToString();
                string cargoName = dt.Rows[i]["CARGONAME"].ToString();
                string cargoNo = dt.Rows[i]["CARGONO"].ToString();

                string ckind_no = dt.Rows[i]["CKINDNO"].ToString();
                string get_owner = dt.Rows[i]["GETOWNER"].ToString();
                string package = dt.Rows[i]["PACKAGE"].ToString();
                string ship_no = dt.Rows[i]["SHIPNO"].ToString();
                items2.Add(new ListItem(billNo, stackName, shipName, cargoName, cargoNo, ckind_no, get_owner, package, ship_no));
            }
            this.comboBox_shipname.DataSource = items2;
            this.comboBox_shipname.ValueMember = "ShipName";
            this.comboBox_shipname.DisplayMember = "DisplayName";
            //////////////////

            string sql_lxh = "select TDH, CARGONO, CARGONAME, STACKNAME, SHIPNO, SHIPNAME, BILLNO, SHIPPER_NAME, GETOWNER  from cargo_thjh order by TDH";

            DataSet dsLXH = ws.getDataSet_Serv(sql_lxh);
            DataTable dtLXH = dsLXH.Tables[0];

            List<ListItem_LX> itemsLX = new List<ListItem_LX>();
            for (int i = 0; i < dtLXH.Rows.Count; i++)
            {
                string tdh = dtLXH.Rows[i]["TDH"].ToString();
                string cargoNo = dtLXH.Rows[i]["CARGONO"].ToString();
                string cargoName = dtLXH.Rows[i]["CARGONAME"].ToString();
                string stackName = dtLXH.Rows[i]["STACKNAME"].ToString();
                string shipNo = dtLXH.Rows[i]["SHIPNO"].ToString();
                string shipName = dtLXH.Rows[i]["SHIPNAME"].ToString();
                string billNo = dtLXH.Rows[i]["BILLNO"].ToString();
                string shipperName = dtLXH.Rows[i]["SHIPPER_NAME"].ToString();
                string getOwner = dtLXH.Rows[i]["GETOWNER"].ToString();
                itemsLX.Add(new ListItem_LX(tdh, cargoNo, cargoName, stackName, shipNo, shipName, billNo, shipperName, getOwner));
            }
            this.comboBoxLXH.DataSource = itemsLX;
            this.comboBoxLXH.ValueMember = "TDH";
            this.comboBoxLXH.DisplayMember = "DisplayName";


            //this.comboBox_shipname.SelectedIndexChanged += new EventHandler(shipname_combobox_changed);
            //this.comboBox_owner.Text = "";
            //this.comboBox_shipname.Text = "";
            this.comboBoxLXH.SelectedIndex = -1;
            this.comboBoxLXH.Text = "";
            this.comboBox_shipname.SelectedIndex = -1;
            this.comboBox_shipname.Text = "";
            this.comboBox_owner.SelectedIndex = -1;
            this.comboBox_owner.Text = "";
            this.comboBox_cargoName.SelectedIndex = -1;
            this.comboBox_cargoName.Text = "";
            this.textBox_billNO.Text = "";
            this.textBox_cargoNo.Text = "";
            this.textBox_stackName.Text = "";
            this.textBox_hc.Text = "";
            this.textBoxPackage.Text = "";
            ckingno_global = "";
            getowner_global = "";

            //Set the car no select groupbox invisible
            lab_car_ok.Text = "";
            groupBox3.Visible = false;
            pnlTCJF.Visible = false;

            InitJFParameter();//初始化计费参数
            InitJFBZCombox();//初始化计费标志下拉列表

            if (ConfigurationManager.AppSettings["TFZH"] == Session.YHBH)
                this.btnRefund.Enabled = true;
            else
                this.btnRefund.Enabled = false;

            if (Session.CanEditLXH)
            {
                this.comboBoxLXH.Enabled = true;
                this.comboBox_shipname.Enabled = true;
            }
            //this.txtBar_Code.Focus();
            this.ActiveControl = this.txtBar_Code;

            UncheckRefresh += new UncheckLabelRereshHandler(fresh_uncheck);
            //定义列表自动刷新
            TruckLogin += new DataGridTruckLoginHandler(Add_DataTable);
            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件；
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件； 
            //Load the 
            load_data();
        }

        /// <summary>
        /// 初始化计费参数
        /// </summary>
        private void InitJFParameter()
        {
            string strConfig = ConfigurationManager.AppSettings["dj"];
            try
            {
                f_DJ = Convert.ToDouble(strConfig);
            }
            catch
            {
                f_DJ = 1;
                MessageBox.Show("计费单价设置错误，已修改为默认值1");
            }
            strConfig = ConfigurationManager.AppSettings["jemin"];
            try
            {
                f_JE_min = Convert.ToDouble(strConfig);
            }
            catch
            {
                f_JE_min = 5;
                MessageBox.Show("最小收费金额设置错误，已修改为默认值5");
            }
            this.txtDJ.Text = f_DJ.ToString();
        }

        private void InitJFBZCombox()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("name", typeof(string));

            dt.Rows.Add(0, "未收");
            dt.Rows.Add(1, "已收");
            dt.Rows.Add(2, "不收");

            cbJFBZ.DataSource = dt;
            cbJFBZ.ValueMember = "id";
            cbJFBZ.DisplayMember = "name";
            cbJFBZ.SelectedValue = 0;
            cbJFBZ.SelectedValueChanged += new EventHandler(cbJFBZ_SelectedValueChanged);
        }

        /// <summary>
        /// 切换计费标志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbJFBZ_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cbJFBZ.SelectedItem != null)
            {
                int jfbz = (int)cbJFBZ.SelectedValue;//计费标志
                if (jfbz == 0 || jfbz == 2)//未收或不收
                {
                    this.txtJE.Text = "0";
                }
                else if (jfbz == 1)//已收
                {
                    string weight = this.txtWeight.Text.Trim();
                    double je = Math.Round(StrToDouble(weight) * f_DJ);
                    je = je < f_JE_min ? f_JE_min : je;
                    this.txtJE.Text = je.ToString();
                }
            }
        }

        void Add_DataTable(DataTable dt)
        {
            this.dataGridView1.AutoGenerateColumns = true;
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.DataSource = dt;

            //设置某些字段不可见
            this.dataGridView1.Columns["IOYARDID"].Visible = false;
            this.dataGridView1.Columns["TRUCKSTATUS"].Visible = false;
            this.dataGridView1.Columns["ID"].Visible = false;
            this.dataGridView1.Columns["DYBZ"].Visible = false;
            this.dataGridView1.Columns["CANCEL_FLAG"].Visible = false;
            SetDefaultColumnWidth();
        }

        void fresh_uncheck(DataTable dt)
        {
            //string new_number = dt.Rows[0][0].ToString();
            this.label_cars.Text = dt.Rows[0][0].ToString();
        }

        public void theout(object source, System.Timers.ElapsedEventArgs e)
        {
            load_data();
            //carssx();
            //string car_no = this.textBox_carNO.Text.ToString().Trim();
            //string sql = "select logintime as 登记时间,CARDTIME as 确认时间,SHIPNAME as 船名,BILL_NO as 提单号,cargoname as 货名,truckno as  车号,qdcardnum as 卡号,DECODE(to_number(TRUCKSTATUS),0,'登记',1,'发指令',2,'确认',3,'已进门',4,'已理货',5,'已出门') as 状态,pieces as 件数,DRIVERPHONE as 电话,cardadd as 登记地点,IOYARDID,TRUCKSTATUS,ID,DYBZ,YARD AS 地点,ZYJX AS 机械 from TRUCK_CARGO_LOGIN" +
            //    " where (TRUCKSTATUS='0' or TRUCKSTATUS='1' or TRUCKSTATUS='2') and ioyardid=0 and cardadd='" + card_add + "'order by TRUCKSTATUS,logintime desc";
            //DataSet ds = ws.getDataSet_Serv(sql);
            //string sql_un = "select count(*) as un_check from TRUCK_CARGO_LOGIN where TRUCKSTATUS='1' and IOYARDID='0'and cardadd='" + card_add + "'";
            //DataSet ds_uncheck = ws.getDataSet_Serv(sql_un);
            //if (this.IsHandleCreated)
            //{
            //    this.dataGridView1.BeginInvoke(TruckLogin, ds.Tables[0]);
            //    this.label_cars.BeginInvoke(UncheckRefresh, ds_uncheck.Tables[0]);
            //}
        }

        private void SetDefaultColumnWidth()
        {
            this.dataGridView1.Columns["流向号"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["货名"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["车号"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["卡号"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["状态"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["登记地点"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["包装"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["条码号"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["计费标志"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
        }

        private string CycleFilter()
        {
            if (IsCycel)
                return " and ISCYCLE='1'";
            return "";
        }

        //the selected index changed event handler for combobox_shipname
        private void button_exist_Click(object sender, EventArgs e)
        {
            //this.Close();//Close the current window, that is, "市提车货登记" window.
            if (this.ParentForm != null)
            {
                this.ParentForm.Close();
            }
            else
            {
                this.Close();
            }
        }

        private void btn_car_Click(object sender, EventArgs e)
        {
            groupBox3.Left = this.textBox_carNO.Left + this.groupBox1.Left;

            //this.textBox_cardNO.Left 
            //groupBox3.Top = btn_car.Top + panel1.Top + btn_car.Height - groupBox1.Height;
            groupBox3.Top = this.textBox_carNO.Top + this.groupBox1.Top + 35;
            lab_car_ok.Text = "";
            groupBox3.Visible = true;
            this.textBox_carNO.SelectionStart = this.textBox_carNO.Text.Length;
            this.textBox_carNO.Focus();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            lab_car_ok.Text = "";
            groupBox3.Visible = false;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.textBox_carNO.Text = "";
            this.textBox_carNO.SelectionStart = this.textBox_carNO.Text.Length;
            this.textBox_carNO.Focus();
        }
        #region
        private void label77_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label77.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label76_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label76.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label75_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label75.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label80_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label80.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label79_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label79.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label82_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label82.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label83_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label83.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label88_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label88.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label87_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label87.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label86_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label86.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label85_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label85.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label84_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label84.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label81_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label81.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label18_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label18.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label17_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label17.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label16_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label16.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label15_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label15.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label14_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label14.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label13_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label13.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label24_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label24.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label23_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label23.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label22_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label22.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label21_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label21.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label20_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label20.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label19_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label19.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label30_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label30.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label29_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label29.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label28_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label28.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label27_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label27.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label26_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label26.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label25_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label25.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label36_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label36.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label35_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label35.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label34_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label34.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label33_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label33.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label32_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label32.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label31_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label31.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label42_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label42.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label41_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label41.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label40_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label40.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label39_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label39.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label38_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label38.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label37_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label37.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label48_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label48.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label47_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label47.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label46_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label46.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label45_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label45.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label44_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label44.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label43_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label43.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label54_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label54.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label53_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label53.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label52_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label52.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label51_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label51.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label50_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label50.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label49_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label49.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label60_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label60.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label59_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label59.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label58_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label58.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label57_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label57.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label56_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label56.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label55_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label55.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label66_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label66.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label65_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label65.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label64_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label64.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label63_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label63.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label62_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label62.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label61_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label61.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label72_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label72.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label71_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label71.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label70_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label70.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label69_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label69.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label68_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label68.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label67_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label67.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }

        private void label78_Click(object sender, EventArgs e)
        {
            textBox_carNO.Text = textBox_carNO.Text + label78.Text;
            textBox_carNO.SelectionStart = textBox_carNO.Text.Length;
            textBox_carNO.Focus();
        }
        #endregion

        private void button_clear_Click(object sender, EventArgs e)
        {
            clear_all();
            is_update = false;
        }

        private void button_multiple_Click(object sender, EventArgs e)
        {
            //检查车辆是否在黑名单中，黑名单的车不予保存
            string car_no = this.textBox_carNO.Text.ToString().Trim();
            string driver_identity = this.textBox_identity.Text.ToString().Trim();
            if (car_no.Length > 0 || driver_identity.Length > 0)
            {
                bool is_black = check_black();
                if (is_black)
                {
                    //MessageBox.Show("此车在黑名单中，不能登记!");
                    return;
                }
            }

            string barCode = this.txtBar_Code.Text.ToString();
            if (!string.IsNullOrEmpty(barCode) && DispBarCode(barCode))
            {
                MessageBox.Show("该条码号对应车辆已登记，不能再次登记!");
                return;
            }

            bool is_checked = check_input();//check the input data
            if (!is_checked)
            {
                return;
            }
            string billNo = this.textBox_billNO.Text.ToString();
            string cardNo = this.textBox_cardNO.Text.ToString();
            string carNo = this.textBox_carNO.Text.ToString();
            //string barCode = this.txtBar_Code.Text.ToString();
            string comment = this.textBox_comment.Text.ToString();
            //string shipper = this.comboBox_owner.SelectedValue.ToString();
            string shipper = "";
            if (this.comboBox_owner.SelectedValue != null)
            {
                shipper = this.comboBox_owner.SelectedValue.ToString().Trim();
                owner_is_selected = true;
                owner_index = this.comboBox_owner.SelectedIndex;
            }
            else
            {
                shipper = this.comboBox_owner.Text.ToString().Trim();
                owner_is_selected = false;
            }
            string cargoName = "";
            if (this.comboBox_cargoName.SelectedValue != null)
                cargoName = this.comboBox_cargoName.SelectedValue.ToString();
            else
                cargoName = this.comboBox_cargoName.Text;
            string username = Session.Operator_User;
            //string ship_name = this.comboBox_shipname.SelectedValue.ToString();

            string ship_name = "";
            if (this.comboBox_shipname.SelectedValue != null)
            {
                ship_name = this.comboBox_shipname.SelectedValue.ToString().Trim();
                shipname_is_selected = true;
                shipname_index = this.comboBox_shipname.SelectedIndex;
            }
            else
            {
                ship_name = this.comboBox_shipname.Text.ToString().Trim();
                shipname_is_selected = false;
            }

            string lxh = string.Empty;
            if (this.comboBoxLXH.SelectedValue != null)
            {
                lxh = this.comboBoxLXH.SelectedValue.ToString().Trim();
            }
            else
            {
                lxh = this.comboBoxLXH.Text.ToString().Trim();
            }
            string voyage = this.textBox_hc.Text.ToString();
            string package = this.textBoxPackage.Text.ToString();
            string cargo_no = this.textBox_cargoNo.Text.ToString();
            string stack_name = this.textBox_stackName.Text.ToString();
            string wlw_pieces = this.txtPieces.Text.Trim();
            string wlw_weight = this.txtWeight.Text.Trim();

            string driver_name = this.textBox_name.Text.ToString().Trim();
            string driver_phone = this.textBox_phone.Text.ToString().Trim();

            if (this.ckbWLWDR.Checked)//物流网导入的校验字段不能为空
            {
                if (!CheckWlwdrInput(barCode, lxh, ship_name, voyage, billNo, cargoName, cargo_no, stack_name, package))
                    return;
                if (!CheckWlwTHDStatus(barCode))//校验物流网提货单车辆状态和是否作废
                    return;
            }

            string jfbz = this.cbJFBZ.SelectedValue.ToString();
            string dj = this.txtDJ.Text.Trim();
            string je = this.txtJE.Text.Trim();
            //判断计费
            if (!CheckJFStatus(jfbz, je))
            {
                return;
            }
            //判断市提流向
            if (!CheckCargoTHJH(lxh, wlw_weight))
            {
                return;
            }

            string lybz = this.ckbWLWDR.Checked ? "1" : "0";//来源标志：1 物流网导入 0 录入
            string station = this.textBoxStation.Text;

            if (carNo != previous_car_no)//the same car cargo
            {
                if (DispCarNo(carNo))
                {
                    MessageBox.Show("此车已在其他停车场登记，不能再次登记!");
                    return;
                }
                //login_time = this.textBox_loginTime.Text.ToString();
                //string dtime = DateTime.Now.ToString();
                string dtime = ws.GetSysDateTime().ToString();
                this.textBox_loginTime.Text = dtime;
                previous_car_no = carNo;
            }

            //检查拉循环车辆
            //if (CheckCycleTruck(stack_name, carNo, out needSF))
            //{
            //    isCycle = "1";
            //}
            string isCycle = IsCycel ? "1" : "0";
            string needSF = "0";

            bool isAuto = false;
            string strZYJX = "", strYard = "";
            if (CheckAutoSendCar(stack_name, getowner_global, out strYard, out strZYJX))
            {
                isAuto = true;
                if (MessageBox.Show("此车满足自动放行条件，是否自动放行并打印提货单？", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    clear_all();
                    return;
                }
            }

            //Create ID 
            string id = create_id();
            string insert_sql = "insert into TRUCK_CARGO_LOGIN(ID,LOGINTIME,TRUCKNO,IOYARDID,CARGONAME,SHIPPER_NAME," +
                "OPERATOR,TRUCKSTATUS,BILL_NO,QDCARDNUM,REMARK,SHIPNAME,VOYAGE,YARD,CARGONO,STACKNAME,CKINDNO,GETOWNER,PACKAGE,SHIPNO,DRIVERNAME,DRIVERID,DRIVERPHONE,CARDADD," +
                "lxh,BAR_CODE,lybz,PIECES,WEIGHT,SETOWNER,STATION,ISCYCLE,ISSF,ISMULTI,VERSION,JFBZ,DJ,JE) values(" +
                id + ",to_date('" + this.textBox_loginTime.Text.ToString() + "','YYYY-MM-DD HH24:MI:SS'),'" + carNo + "','0','" + cargoName +
                "','" + shipper + "','" + username + "','0','" + billNo + "','" + cardNo + "','" + comment + "','" + ship_name + "','" + voyage + "','" + wlw_yard + "','" + cargo_no + "','" +
                stack_name + "','" + ckingno_global + "','" + getowner_global + "','" + package + "'," + shipno_global + ",'" + driver_name + "','" + driver_identity + "','" + driver_phone +
                "','" + card_add + "','" + lxh + "','" + barCode + "','" + lybz + "','" + wlw_pieces + "','" + wlw_weight + "','" + wlw_setowner + "','" + station +
                "','" + isCycle + "','" + needSF + "','1','" + strVersion + "','" + jfbz + "','" + dj + "','" + je + "')";
            int ret = ws.execute_UID_Serv(insert_sql);
            if (ret > 0 && lybz == "1" && !string.IsNullOrEmpty(barCode))
            {
                string strSQL = "insert into TRUCK_WEIGH_FLAG(TRUCKNO,BAR_CODE,WEIGH_FLAG,CZSJ) values('" + carNo + "','" + barCode + "','4',sysdate)";
                ret = ws.execute_UID_Serv(strSQL);
            }
            if (lybz == "1")
            {
                
            }
            
            if (isAuto)
            {
                AutoSendCar(id, carNo, barCode, lybz, strYard, strZYJX);//自动放车
            }
            else
            {
                MessageBox.Show("保存成功，请录入下一票数据！");
            }
            clear_second_section();//Clear the second section input box content
            load_data();
        }

        /// <summary>
        /// 判断是否满足自动放车条件
        /// </summary>
        /// <param name="stackname"></param>
        /// <param name="getowner"></param>
        /// <returns></returns>
        private bool CheckAutoSendCar(string stackname, string getowner, out string yard, out string zyjx)
        {
            bool result = false;
            yard = string.Empty;
            zyjx = string.Empty;
            string strSQL = "select id,zyjx,yard from TRUCK_AUTO_SENDCAR where stackname='" + stackname + "' and getowner='" + getowner + "'";
            DataTable dt = ws.getDataSet_Serv(strSQL).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                yard = dt.Rows[0]["yard"].ToString();
                zyjx = dt.Rows[0]["zyjx"].ToString();
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 自动放车，并打印提货单
        /// </summary>
        /// <param name="strID"></param>
        /// <param name="strTruckNo"></param>
        /// <param name="strBarCode"></param>
        /// <param name="strLYBZ"></param>
        private void AutoSendCar(string strID, string strTruckNo, string strBarCode, string strLYBZ, string yard, string zyjx)
        {
            //放车
            String update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=2,CARDTIME=sysdate,ISAUTO='1',YARD='" + yard + "',ZYJX='" + zyjx + "' where id = " + strID + "";
            int ret1 = ws.execute_UID_Serv(update_sql);
            if (ret1 < 0)
            {
                MessageBox.Show("自动放车失败！");
                return;
            }
            //记录日志
            string new_id = create_id();
            string op_user = Session.Operator_User.ToString();
            string insert_sql = "insert into TRUCK_LOG(ID,TRUCKNO,OPERATENAME,XGSJ,XGNR) values(" + new_id +
                ",'" + strTruckNo + "','" + op_user + "',sysdate,'停车场自动放车确认')";
            int ret2 = ws.execute_UID_Serv(insert_sql);
            //if (ret2 < 0) return;
            if (strLYBZ == "1" && !string.IsNullOrEmpty(strBarCode))//物流网登记的
            {
                //更新物流网提货单状态
                string update_wlw_sql = "delete from TRUCK_WEIGH_FLAG where bar_code = '" + strBarCode + "'";
                ws.execute_UID_Serv(update_wlw_sql);
                update_wlw_sql = "insert into TRUCK_WEIGH_FLAG(TRUCKNO,BAR_CODE,WEIGH_FLAG,CZSJ) values('" + strTruckNo + "','" + strBarCode + "','5',sysdate)";
                ws.execute_UID_Serv(update_wlw_sql);
                //打提货单
                PrintCode pc = new PrintCode();
                pc.Run_QYD(strID);
            }
            else if (strLYBZ == "0") //停车场登记的，打印小票
            {
                PrintCode pc = new PrintCode();
                pc.Run(strID, "大港公司市提车辆登记小票");
            }
        }

        private bool DispCarNo(string _carno)
        {
            StringBuilder sbsql = new StringBuilder();
            sbsql.AppendFormat("SELECT ID FROM TRUCK_CARGO_LOGIN WHERE TRUCKNO ='{0}' AND  TRUCKSTATUS='0' AND coalesce(CANCEL_FLAG,'0')<>'1'", _carno);
            if (ws.getDataSet_Serv(sbsql.ToString()).Tables[0].Rows.Count > 0)
            {
                return true;
            }
            return false;
        }

        private bool DispBarCode(string barcode)
        {
            string strSQL = string.Format("SELECT ID FROM TRUCK_CARGO_LOGIN WHERE bar_code = '{0}' AND  TRUCKSTATUS <> '9'", barcode);
            if (ws.getDataSet_Serv(strSQL).Tables[0].Rows.Count > 0)
            {
                return true;
            }
            return false;
        }

        //private bool CheckCycleTruck(string stackname, string truckno, out string needSF)
        //{
        //    needSF = "0";
        //    bool result = false;
        //    if (!string.IsNullOrEmpty(stackname) && !string.IsNullOrEmpty(truckno))
        //    {
        //        string strSQL = "select ID,SFTIME from TRUCK_CYCLE_STACK_MX where ISDEL='0' and STACKNAME='" + stackname + "' and TRUCKNO = '" + truckno + "'";
        //        DataTable dtCycle = ws.getDataSet_Serv(strSQL).Tables[0];
        //        if (dtCycle != null && dtCycle.Rows.Count > 0)
        //        {
        //            result = true;
        //            DateTime dtSF = ObjToDateTime(dtCycle.Rows[0]["SFTIME"]);
        //            if (dtSF.AddHours(24) <= DateTime.Now)
        //            {
        //                string stTime = "";
        //                if (dtSF != DateTime.MinValue)
        //                    stTime = dtSF.ToString();
        //                MessageBox.Show("该车为拉循环车辆，本次应收费！上次收费时间：" + stTime);
        //                needSF = "1";
        //                ws.execute_UID_Serv("update TRUCK_CYCLE_STACK_MX set SFTIME=SYSDATE where ID = " + dtCycle.Rows[0]["ID"].ToString());
        //            }
        //        }
        //    }
        //    return result;
        //}

        private string CheckCycleTruckSF(string strShipNo, string strShipName, string strTruckNo)
        {
            string strNeedSF = "0";
            if (!string.IsNullOrEmpty(strShipNo) && !string.IsNullOrEmpty(strShipName) && !string.IsNullOrEmpty(strTruckNo))
            {
                DateTime dtNow = ws.GetSysDateTime();
                string strSQL = "select max(LOGINTIME) sftime from v_truck_cargo_login_all where shipno='" + strShipNo + "' and shipname='" + strShipName + "' and truckno='" + strTruckNo +
                    "' and ISSF='1' and iscycle='1' and ioyardid='0' and truckstatus<>'9'";
                DataTable dtCycle = ws.getDataSet_Serv(strSQL).Tables[0];
                if (dtCycle != null && dtCycle.Rows.Count > 0 && !string.IsNullOrEmpty(dtCycle.Rows[0]["sftime"].ToString()))
                {
                    DateTime dtSF = DateTime.Parse(dtCycle.Rows[0]["sftime"].ToString());
                    if (dtSF.AddDays(1) <= dtNow)
                    {
                        MessageBox.Show("该车本次登记应收费，上次收费时间：" + dtSF.ToString());
                        strNeedSF = "1";
                    }
                }
                else//兼容一下历史数据
                {
                    strSQL = "select min(LOGINTIME) firsttime from v_truck_cargo_login_all where shipno='" + strShipNo + "' and shipname='" + strShipName + "' and truckno='" + strTruckNo +
                        "' and iscycle='1' and ioyardid='0' and truckstatus<>'9'";
                    dtCycle = ws.getDataSet_Serv(strSQL).Tables[0];
                    if (dtCycle != null && dtCycle.Rows.Count > 0 && !string.IsNullOrEmpty(dtCycle.Rows[0]["firsttime"].ToString()))
                    {
                        DateTime dtSF = DateTime.Parse(dtCycle.Rows[0]["firsttime"].ToString());//首次登记时间
                        return CheckCycleTruckSF_His(dtSF, dtNow, strShipNo, strShipName, strTruckNo);
                    }
                    else
                    {
                        MessageBox.Show("该车本轮循环首次登记，应收费！");
                        strNeedSF = "1";
                    }
                }
            }
            return strNeedSF;
        }

        private string CheckCycleTruckSF_His(DateTime dtLastTime, DateTime dtNow, string strShipNo, string strShipName, string strTruckNo)
        {
            DateTime dtNextTime = dtLastTime.AddDays(1);
            if (dtNextTime > dtNow)
            {
                return "0";
            }
            string strSQL = "select min(LOGINTIME) sftime from v_truck_cargo_login_all where shipno='" + strShipNo + "' and shipname='" + strShipName + "' and truckno='" + strTruckNo +
                "' and iscycle='1' and ioyardid='0' and truckstatus<>'9' and logintime >= to_date('" + dtNextTime + "','yyyy-mm-dd hh24:mi:ss')";
            DataTable dtCycle = ws.getDataSet_Serv(strSQL).Tables[0];
            if (dtCycle != null && dtCycle.Rows.Count > 0 && !string.IsNullOrEmpty(dtCycle.Rows[0]["sftime"].ToString()))
            {
                DateTime dtSF = DateTime.Parse(dtCycle.Rows[0]["sftime"].ToString());
                return CheckCycleTruckSF_His(dtSF, dtNow, strShipNo, strShipName, strTruckNo);
            }
            else
            {
                MessageBox.Show("该车本次登记应收费，上次收费时间：" + dtLastTime.ToString());
                return "1";
            }
        }

        private DateTime ObjToDateTime(object obj)
        {
            try
            {
                return Convert.ToDateTime(obj);
            }
            catch
            {
                return DateTime.MinValue;
            }
        }

        private bool CheckJFStatus(string jfbz, string je)
        {
            double jfje = 0;
            try
            {
                jfje = Convert.ToDouble(je);
            }
            catch
            {
                MessageBox.Show("金额不是有效的数字！");
                return false;
            }
            if (jfbz == "0")//未收
            {
                MessageBox.Show("请进行计费！");
                return false;
            }
            //double jfje = StrToDouble(je);
            if (jfbz == "2" && jfje > 0)//不收
            {
                MessageBox.Show("计费标志与收费金额不一致！");
                return false;
            }
            if (jfbz == "1" && jfje < f_JE_min)//已收
            {
                MessageBox.Show("收费金额最少为：" + f_JE_min);
                return false;
            }
            return true;
        }

        private void button_save_Click(object sender, EventArgs e)
        {
            //检查车辆是否在黑名单中，黑名单的车不予保存
            string car_no = this.textBox_carNO.Text.ToString().Trim();
            string driver_identity = this.textBox_identity.Text.ToString().Trim();
            if (car_no.Length > 0 || driver_identity.Length > 0)
            {
                bool is_black = check_black();
                if (is_black)
                {
                    //MessageBox.Show("此车在黑名单中，不能登记!");
                    return;
                }
            }

            if (DispCarNo(car_no))
            {
                MessageBox.Show("此车已在其他停车场登记，不能再次登记!");
                return;
            }

            string barCode = this.txtBar_Code.Text.ToString();
            if (!string.IsNullOrEmpty(barCode) && DispBarCode(barCode))
            {
                MessageBox.Show("该条码号对应车辆已登记，不能再次登记!");
                return;
            }

            bool is_checked = check_input();//check the input data
            if (!is_checked)
            {
                return;
            }
            string billNo = this.textBox_billNO.Text.ToString();
            string cardNo = this.textBox_cardNO.Text.ToString();
            string carNo = this.textBox_carNO.Text.ToString();
            string comment = this.textBox_comment.Text.ToString();
            //string shipper = this.comboBox_owner.SelectedValue.ToString();
            string shipper = "";
            if (this.comboBox_owner.SelectedValue != null)
            {
                shipper = this.comboBox_owner.SelectedValue.ToString().Trim();
                owner_is_selected = true;
                owner_index = this.comboBox_owner.SelectedIndex;
            }
            else
            {
                shipper = this.comboBox_owner.Text.ToString().Trim();
                owner_is_selected = false;
            }
            //string cargoName = this.comboBox_cargoName.SelectedValue.ToString();
            string cargoName = "";
            if (this.comboBox_cargoName.SelectedValue != null)
                cargoName = this.comboBox_cargoName.SelectedValue.ToString();
            else
                cargoName = this.comboBox_cargoName.Text;
            //string cargoName = this.comboBox_cargoName.Text.ToString();
            string username = Session.Operator_User;

            //string ship_name = this.comboBox_shipname.SelectedValue.ToString();
            string ship_name = "";
            if (this.comboBox_shipname.SelectedValue != null)
            {
                ship_name = this.comboBox_shipname.SelectedValue.ToString().Trim();
                shipname_is_selected = true;
                shipname_index = this.comboBox_shipname.SelectedIndex;
            }
            else
            {
                ship_name = this.comboBox_shipname.Text.ToString().Trim();
                shipname_is_selected = false;
            }

            string lxh = string.Empty;
            if (this.comboBoxLXH.SelectedValue != null)
            {
                lxh = this.comboBoxLXH.SelectedValue.ToString().Trim();
            }
            else
            {
                lxh = this.comboBoxLXH.Text.ToString().Trim();
            }

            string voyage = this.textBox_hc.Text.ToString();
            string package = this.textBoxPackage.Text.ToString();
            string cargo_no = this.textBox_cargoNo.Text.ToString();
            string stack_name = this.textBox_stackName.Text.ToString();
            string wlw_pieces = this.txtPieces.Text.Trim();
            string wlw_weight = this.txtWeight.Text.Trim();

            string driver_name = this.textBox_name.Text.ToString().Trim();
            string driver_phone = this.textBox_phone.Text.ToString().Trim();

            if (this.ckbWLWDR.Checked)//物流网导入的校验字段不能为空
            {
                if (!CheckWlwdrInput(barCode, lxh, ship_name, voyage, billNo, cargoName, cargo_no, stack_name, package))
                    return;
                if (!CheckWlwTHDStatus(barCode))//校验物流网提货单车辆状态和是否作废
                    return;
            }

            string jfbz = this.cbJFBZ.SelectedValue.ToString();
            string dj = this.txtDJ.Text.Trim();
            string je = this.txtJE.Text.Trim();
            //判断计费
            if (!CheckJFStatus(jfbz, je))
            {
                return;
            }
            //判断市提流向
            if (!CheckCargoTHJH(lxh, wlw_weight))
            {
                return;
            }

            string lybz = this.ckbWLWDR.Checked ? "1" : "0";//来源标志：1 物流网导入 0 录入
            string station = this.textBoxStation.Text;

            string dtime = ws.GetSysDateTime().ToString();
            this.textBox_loginTime.Text = dtime;

            if (carNo != previous_car_no)//the same car cargo
            {
                //login_time = this.textBox_loginTime.Text.ToString();
                previous_car_no = carNo;
            }

            //拉循环车辆
            string isCycle = "0", needSF = "0";
            if (IsCycel)
            {
                isCycle = "1";
                needSF = CheckCycleTruckSF(shipno_global, ship_name, carNo);
            }

            //if (is_update)
            //{
            //    string sql_update = "update TRUCK_CARGO_LOGIN set QDCARDNUM='" + cardNo + "',TRUCKNO='" + carNo + "',SHIPPER_NAME='" + shipper + "',SHIPNAME='" + ship_name + "',VOYAGE='" + voyage
            //        + "',BILL_NO='" + billNo + "',CARGONAME='" + cargoName + "',CARGONO='" + cargo_no + "',STACKNAME='" + stack_name + "',REMARK='" + comment +
            //        "',DRIVERNAME='" + driver_name + "',DRIVERID='" + driver_identity + "',DRIVERPHONE='" + driver_phone + "',PACKAGE='" + package + "',lxh='" + lxh +
            //        "',BAR_CODE='" + barCode + "',lybz='" + lybz + "',STATION='" + station + "' where id='" + update_id + "'";
            //    ws.execute_UID_Serv(sql_update);
            //    is_update = false;
            //}
            //else {
            //Create ID 

            bool isAuto = false;
            string strZYJX = "", strYard = "";
            if (CheckAutoSendCar(stack_name, getowner_global, out strYard, out strZYJX))
            {
                isAuto = true;
                if (MessageBox.Show("此车满足自动放行条件，是否自动放行并打印提货单？", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    clear_all();
                    return;
                }
            }

            string id = create_id();
            string insert_sql = "insert into TRUCK_CARGO_LOGIN(ID,LOGINTIME,TRUCKNO,IOYARDID,CARGONAME,SHIPPER_NAME," +
                "OPERATOR,TRUCKSTATUS,BILL_NO,QDCARDNUM,REMARK,SHIPNAME,VOYAGE,YARD,CARGONO,STACKNAME,CKINDNO,GETOWNER,PACKAGE,SHIPNO,DRIVERNAME,DRIVERID,DRIVERPHONE,CARDADD," +
                "lxh,BAR_CODE,lybz,PIECES,WEIGHT,SETOWNER,STATION,ISCYCLE,ISSF,ISMULTI,VERSION,JFBZ,DJ,JE) values(" +
                id + ",to_date('" + this.textBox_loginTime.Text.ToString() + "','YYYY-MM-DD HH24:MI:SS'),'" + carNo + "','0','" + cargoName +
                "','" + shipper + "','" + username + "','0','" + billNo + "','" + cardNo + "','" + comment + "','" + ship_name + "','" + voyage + "','" + wlw_yard + "','" + cargo_no +
                "','" + stack_name + "','" + ckingno_global + "','" + getowner_global + "','" + package + "'," + shipno_global + ",'" + driver_name + "','" + driver_identity +
                "','" + driver_phone + "','" + card_add + "','" + lxh + "','" + barCode + "','" + lybz + "','" + wlw_pieces + "','" + wlw_weight + "','" + wlw_setowner + "','" + station +
                "','" + isCycle + "','" + needSF + "','0','" + strVersion + "','" + jfbz + "','" + dj + "','" + je + "')";
            int ret = ws.execute_UID_Serv(insert_sql);
            if (ret > 0 && lybz == "1" && !string.IsNullOrEmpty(barCode))
            {
                string strSQL = "insert into TRUCK_WEIGH_FLAG(TRUCKNO,BAR_CODE,WEIGH_FLAG,CZSJ) values('" + carNo + "','" + barCode + "','4',sysdate)";
                ret = ws.execute_UID_Serv(strSQL);
            }

            if (lybz == "1")
            {
                String update_sql = "update dg_car_thjh set weigh_flag=4 where BAR_CODE='" + barCode + "'";
                int ret1 = ws.execute_UID_Serv(update_sql);
                //******************************************************//
                //顺便调用电商平台的webservice，更新电商平台的车辆状态。//
                //******************************************************//
                HttpReValue rv = HttpClass.PostWebApiResult<HttpReValue>(wawrdout + string.Format("?bar_code={0}&car_state={1}", barCode, 4));
                
                if (rv.type != "success")
                {
                    MessageBox.Show(rv.content);
                    //return;
                }
                
            }
           
            if (isAuto)
            {
                AutoSendCar(id, carNo, barCode, lybz, strYard, strZYJX);//自动放车
            }
            else
            {
                MessageBox.Show("保存成功！");
            }
            clear_all();//Clear all input box content
            load_data();
        }

        //Clear all input box in the window
        private void clear_all()
        {
            this.comboBox_owner.SelectedIndex = -1;
            this.comboBoxLXH.SelectedIndex = -1;
            this.comboBox_shipname.SelectedIndex = -1;
            this.comboBox_cargoName.SelectedIndex = -1;

            this.textBox_billNO.Text = "";
            this.textBox_cardNO.Text = "";
            this.textBox_carNO.Text = "";
            this.txtBar_Code.Text = "";
            this.textBox_comment.Text = "";
            this.textBox_hc.Text = "";
            this.textBoxPackage.Text = "";
            this.comboBox_owner.Text = "";
            //Set login time again
            //string dtime = DateTime.Now.ToString();
            //this.textBox_loginTime.Text = dtime;

            this.comboBoxLXH.Text = "";
            this.comboBox_shipname.Text = "";
            this.comboBox_cargoName.Text = "";
            this.textBox_cargoNo.Text = "";
            this.textBox_stackName.Text = "";

            this.textBox_name.Text = "";
            this.textBox_identity.Text = "";
            this.textBox_phone.Text = "";
            this.textBoxStation.Text = "";

            this.ckbWLWDR.Checked = true;

            this.txtPieces.Text = "";
            this.txtWeight.Text = "";
            this.cbJFBZ.SelectedValue = 0;
            this.txtDJ.Text = f_DJ.ToString();
            this.txtJE.Text = "0";

            wlw_yard = string.Empty;
            //wlw_pieces = string.Empty;
            //wlw_weight = string.Empty;
            wlw_setowner = string.Empty;
            getowner_global = "";
        }

        //Clear the second section input box content in the window
        private void clear_second_section()
        {
            this.comboBoxLXH.SelectedIndex = -1;
            this.comboBox_shipname.SelectedIndex = -1;

            this.textBox_billNO.Text = "";
            this.textBox_comment.Text = "";
            this.textBox_hc.Text = "";
            this.textBoxPackage.Text = "";
            this.comboBoxLXH.Text = "";
            this.comboBox_shipname.Text = "";
            this.comboBox_cargoName.Text = "";
            this.textBox_cargoNo.Text = "";
            this.textBox_stackName.Text = "";
            this.textBoxStation.Text = "";

            //this.ckbWLWDR.Checked = false;
            this.txtBar_Code.Text = "";

            this.txtPieces.Text = "";
            this.txtWeight.Text = "";
            this.cbJFBZ.SelectedValue = 0;
            this.txtDJ.Text = f_DJ.ToString();
            this.txtJE.Text = "0";

            wlw_yard = string.Empty;
            //wlw_pieces = string.Empty;
            //wlw_weight = string.Empty;
            wlw_setowner = string.Empty;
            getowner_global = "";
        }
        //Create ID
        private string create_id()
        {
            string sequence = "";
            string sqlStr = "select SEQ_TRUCK.nextval from dual";
            DataSet ds1 = ws.getDataSet_Serv(sqlStr);
            if (ds1.Tables[0].Rows.Count > 0)
            {
                sequence = ds1.Tables[0].Rows[0][0].ToString();
            }
            string year_str = DateTime.Now.Year.ToString();
            string month_str = DateTime.Now.Month.ToString();
            string day_str = DateTime.Now.Day.ToString();
            //string hour_str = DateTime.Now.Hour.ToString();
            //string minute_str = DateTime.Now.Minute.ToString();
            //string second_str = DateTime.Now.Second.ToString();
            //string id = year_str + month_str + day_str + hour_str + minute_str + second_str + sequence;
            string id = year_str + month_str + day_str + sequence;
            return id;
        }
        //check input data
        private bool check_input()
        {
            string car_no = this.textBox_carNO.Text.ToString().Trim();
            string card_no = this.textBox_cardNO.Text.ToString().Trim();
            string driver_identity = this.textBox_identity.Text.ToString().Trim();

            if (car_no.Length == 0)
            {
                MessageBox.Show("车号不允许为空!");
                this.textBox_carNO.Focus();
                return false;
            }
            if (card_no.Length == 0)
            {
                MessageBox.Show("卡号不允许为空!");
                this.textBox_cardNO.Focus();
                return false;
            }
            //
            if (driver_identity.Length != 18)
            {
                MessageBox.Show("身份证号位数应该为18位!");
                this.textBox_identity.Focus();
                return false;
            }
            //货主代理与船名必须有一项不为空的检验
            //string ship_name = "";
            //if (this.comboBox_shipname.SelectedValue != null)
            //{
            //    ship_name = this.comboBox_shipname.SelectedValue.ToString().Trim();
            //}
            //else
            //{
            //    ship_name = this.comboBox_shipname.Text.ToString().Trim();
            //}
            string shipper = "";
            if (this.comboBox_owner.SelectedValue != null)
            {
                shipper = this.comboBox_owner.SelectedValue.ToString().Trim();
            }
            else
            {
                shipper = this.comboBox_owner.Text.ToString().Trim();
            }
            if (string.IsNullOrEmpty(shipper))
            {
                MessageBox.Show("货主代理(发货人)不允许为空!");
                this.comboBox_owner.Focus();
                return false;
            }
            if (cbJFBZ.SelectedItem == null)
            {
                MessageBox.Show("计费标志不允许为空!");
                this.cbJFBZ.Focus();
                return false;
            }
            //if (ship_name.Length == 0 && shipper.Length == 0)
            //{
            //    MessageBox.Show("货主代理和船名必须有一项不为空!");
            //    this.comboBox_owner.Focus();
            //    return false;
            //}
            return true;
        }

        private bool CheckWlwdrInput(string barcode, string lxh, string cm, string hc, string tdh, string hm, string hh, string dm, string bz)
        {
            if (string.IsNullOrEmpty(barcode))
            {
                MessageBox.Show("物流网导入的数据条码号不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(lxh))
            {
                MessageBox.Show("物流网导入的数据流向号不能为空！");
                return false;
            }
            //if (string.IsNullOrEmpty(cm))
            //{
            //    MessageBox.Show("物流网导入的数据船名不能为空！");
            //    return false;
            //}
            //if (string.IsNullOrEmpty(hc))
            //{
            //    MessageBox.Show("物流网导入的数据航次不能为空！");
            //    return false;
            //}
            //if (string.IsNullOrEmpty(tdh))
            //{
            //    MessageBox.Show("物流网导入的数据提单号不能为空！");
            //    return false;
            //}
            if (string.IsNullOrEmpty(hm))
            {
                MessageBox.Show("物流网导入的数据货名不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(hh))
            {
                MessageBox.Show("物流网导入的数据货号不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(dm))
            {
                MessageBox.Show("物流网导入的数据垛名不能为空！");
                return false;
            }
            //if (string.IsNullOrEmpty(bz))
            //{
            //    MessageBox.Show("物流网导入的数据包装不能为空！");
            //    return false;
            //}
            return true;
        }

        private bool CheckWlwTHDStatus(string bar_code)
        {
            string sql = "SELECT cancel_flag,coalesce(weigh_flag, '0') as weigh_flag FROM DG_CAR_THJH WHERE BAR_CODE = '" + bar_code + "' ORDER BY PLANDATE DESC";
            DataSet dsWLW = ws.getDataSet_Serv(sql);
            if (dsWLW.Tables[0].Rows.Count > 0)
            {
                DataRow row = dsWLW.Tables[0].Rows[0];
                if (row["cancel_flag"].ToString() == "1")
                {
                    MessageBox.Show("提货单已经作废，不能登记！");
                    return false;
                }
                //if (row["weigh_flag"].ToString() != "0")
                //{
                //    MessageBox.Show("物流网提货单车辆状态不正确，不能登记！");
                //    return false;
                //}
            }
            return true;
        }

        #region check blacklist
        //Check the car whether is in black list
        private bool check_black()
        {
            string car_no = this.textBox_carNO.Text.ToString().Trim();
            if (check_black(car_no))
            {
                MessageBox.Show("此车在黑名单中，不能登记!");
                return true;
            }
            string identiry = this.textBox_identity.Text.ToString().Trim();
            if (check_black(identiry))
            {
                MessageBox.Show("此身份证号在黑名单中，不能登记!");
                return true;
            }
            return false;
        }

        private bool check_black(string truckNo)
        {
            string get_black_car = "select * from TRUCK_BLACK_NEW where TRUCKNO='" + truckNo + "'";
            DataSet ds_black = ws.getDataSet_Serv(get_black_car);
            return (ds_black.Tables[0].Rows.Count > 0);
        }

        private void textBox_identity_Leave(object sender, EventArgs e)
        {
            string identiry = this.textBox_identity.Text.ToString().Trim();
            if (identiry.Length > 0)
            {
                bool is_black = check_black(identiry);
                if (is_black)
                {
                    MessageBox.Show("此身份证号在黑名单中，不能登记!");
                    return;
                }
            }
        }
        #endregion

        //Check the card status by the car no
        private void check_car_by_no()
        {
            string car_no = this.textBox_carNO.Text.ToString().Trim();
            string get_car = "select XLH,CARDID,CHEHAO,CARDSTATE from RFID_READ where cardstate='0' and CHEHAO='" + car_no + "' and BS is null";
            DataSet ds_car = ws.getDataSet_Serv(get_car);

            if (ds_car.Tables[0].Rows.Count > 0)
            {
                string card_no = ds_car.Tables[0].Rows[0]["XLH"].ToString().Trim();
                this.textBox_cardNO.Text = card_no;
                //is_new_card = false;
                //检查该卡是否已经作废
                string cardstate = ds_car.Tables[0].Rows[0]["CARDSTATE"].ToString();
                if (cardstate == "1")
                {
                    textBox_carNO.Text = "";
                    MessageBox.Show("该卡已经作废，请重新发卡!");
                    return;
                }
            }
            else
            {
                is_new_card = true;
                this.textBox_cardNO.Text = "";
                MessageBox.Show("该车没有发卡，请为该车发卡!");
            }
            return;
        }

        private void textBox_carNO_Leave(object sender, EventArgs e)
        {
            string car_no = this.textBox_carNO.Text.ToString().Trim();
            if (car_no.Length > 0)
            {
                bool is_black = check_black(car_no);
                if (is_black)
                {
                    MessageBox.Show("此车在黑名单中，不能登记!");
                    return;
                }
            }
            check_car_by_no();//check the status of car
            if (this.ckbWLWDR.Checked && !isImport)
            {
                CheckWlwByCarNo();//检测物流网导入
            }
            return;
        }

        private void textBox_cardNO_Leave(object sender, EventArgs e)
        {
            string card_no = this.textBox_cardNO.Text.ToString().Trim();
            if (card_no.Length > 0)
            {
                string get_car = "select XLH,CARDID,CHEHAO,CARDSTATE from RFID_READ where XLH='" + card_no + "' and BS is null";
                DataSet ds_car = ws.getDataSet_Serv(get_car);

                //DataSet ds_car = get_car_dataset();
                if (ds_car.Tables[0].Rows.Count > 0)
                {
                    string car_no = ds_car.Tables[0].Rows[0]["CHEHAO"].ToString().Trim();
                    if (car_no.Length == 0)
                    {
                        is_new_card = true;
                        this.textBox_carNO.Text = "";
                        MessageBox.Show("该车没有发卡，请为该车发卡!");
                    }
                    else
                    {
                        is_new_card = false;
                        this.textBox_carNO.Text = car_no;
                    }
                    //检查该卡是否已经作废
                    string cardstate = ds_car.Tables[0].Rows[0]["CARDSTATE"].ToString();
                    if (cardstate == "1")
                    {
                        textBox_cardNO.Text = "";
                        MessageBox.Show("该卡已经作废，请重新发卡!");
                        return;
                    }
                }
                else
                {
                    is_new_card = false;
                    this.textBox_cardNO.Text = "";
                    //can not find the record in the RFID_READ table by the serial NO.
                    MessageBox.Show("输入的序列号有误，请重新输入!");
                }
                //带出司机姓名,电话和身份证信息
                //string get_driver_info = "select DRIVERNAME as 姓名,DRIVERID as 身份证,DRIVERPHONE as 电话 from V_TRUCK_CARGO_LOGIN_ALL where QDCARDNUM='" + card_no + "' and  DRIVERNAME is not null order by logintime desc";
                //string get_driver_info = "select distinct DRIVERNAME as 姓名,DRIVERID as 身份证,DRIVERPHONE as 电话 from V_TRUCK_CARGO_LOGIN_ALL where QDCARDNUM='" + card_no + "' and  DRIVERNAME is not null";
                string get_driver_info = "select DRIVERNAME as 姓名,DRIVERID as 身份证,DRIVERPHONE as 电话 from (" +
                    "select ROW_NUMBER() OVER(PARTITION BY DRIVERPHONE ORDER BY LOGINTIME desc) as seqNo,t.* from V_TRUCK_CARGO_LOGIN_ALL t where QDCARDNUM = '" + card_no + "' and DRIVERNAME is not null order by logintime desc" +
                    ") where seqNo = 1 and rownum <=3";
                //select *, count(distinct name) from table group by name
                DataSet ds_drivers = ws.getDataSet_Serv(get_driver_info);
                if (ds_drivers.Tables[0].Rows.Count > 0)
                {
                    Drivers divers = new Drivers();
                    Drivers.divers = ds_drivers;
                    divers.ShowDialog(this);
                    this.textBox_name.Text = divers.driver_name;
                    this.textBox_identity.Text = divers.driver_id;
                    this.textBox_phone.Text = divers.driver_phone;
                }
            }
            return;
        }

        private void txtBar_Code_Leave(object sender, EventArgs e)
        {
            if (this.ckbWLWDR.Checked && !isImport)
            {
                CheckWlwByBarCode();//检测物流网导入
            }
        }


        private void btnImport_Click(object sender, EventArgs e)
        {
            if (this.ckbWLWDR.Checked && !isImport)
            {
                if (string.IsNullOrEmpty(this.txtBar_Code.Text.ToString().Trim()))
                {
                    MessageBox.Show("请输入条码号！");
                }
                else
                {
                    CheckWlwByBarCode();//检测物流网导入
                }
            }
        }

        #region 检查物流网导入
        private void CheckWlwByCarNo()
        {
            string car_no = this.textBox_carNO.Text.ToString().Trim();
            if (car_no.Length > 0)
            {
                string sql =
                    "SELECT CARNO,DRIVER_NAME,DRIVER_IDCARD,DRIVER_TEL,STACKNAME,CARGONAME,CARGONO,SHIPPER_NAME,CARGO_PLACE,CAR_PIECES,CAR_WEIGHT,SHIPNAME," +
                    "SETOWNER,BILLNO,RFID_NO,GETOWNER,PACK,SHIPNO,BAR_CODE,TDH,STATION,cancel_flag,coalesce(weigh_flag, '0') as weigh_flag " +
                    "FROM DG_CAR_THJH WHERE CARNO = '" + car_no + "' ORDER BY PLANDATE DESC";
                DataSet dsWLW = ws.getDataSet_Serv(sql);
                if (dsWLW.Tables[0].Rows.Count > 0)
                {
                    ImportWlwData(dsWLW.Tables[0].Rows[0]);
                }
                else
                {
                    MessageBox.Show("物流网没有电子提货单，不允许登记收费!");
                }
            }
        }

        private void CheckWlwByBarCode()
        {
            string barcode = this.txtBar_Code.Text.ToString().Trim();
            if (barcode.Length > 0)
            {
                string sql =
                    "SELECT CARNO,DRIVER_NAME,DRIVER_IDCARD,DRIVER_TEL,STACKNAME,CARGONAME,CARGONO,SHIPPER_NAME,CARGO_PLACE,CAR_PIECES,CAR_WEIGHT,SHIPNAME," +
                    "SETOWNER,BILLNO,RFID_NO,GETOWNER,PACK,SHIPNO,BAR_CODE,TDH,STATION,cancel_flag,coalesce(weigh_flag, '0') as weigh_flag " +
                    "FROM DG_CAR_THJH WHERE BAR_CODE = '" + barcode + "' ORDER BY PLANDATE DESC";
                DataSet dsWLW = ws.getDataSet_Serv(sql);
                if (dsWLW.Tables[0].Rows.Count > 0)
                {
                    ImportWlwData(dsWLW.Tables[0].Rows[0]);
                }
                else
                {
                    MessageBox.Show("物流网没有电子提货单，不允许登记收费!");
                }
            }
        }

        private double StrToDouble(string value)
        {
            try
            {
                return Convert.ToDouble(value);
            }
            catch
            {
                return 0;
            }
        }

        //判读市提流向计划是否可放货
        private bool CheckCargoTHJH(string tdh, string weight)
        {
            string ifEnd = "0";
            double weight_jh = 0;
            string sql = "select coalesce(max(ifend),0) ifend,coalesce(sum(weight),0) weight from cargo_thjh where tdh = '" + tdh + "'";
            DataTable dt = ws.getDataSet_Serv(sql).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                ifEnd = dt.Rows[0]["ifend"].ToString();
                weight_jh = StrToDouble(dt.Rows[0]["weight"].ToString());
            }
            //判断流向是否已完标
            if (ifEnd == "1")
            {
                MessageBox.Show("该流向已完标，请与开发科联系！");
                return false;
            }
            //判断车辆计划吨数是否超出流向余数或实际余数
            double car_weight = StrToDouble(weight);
            sql = "select sum(weight) from v_login_jlb_dj where lxh='" + tdh + "'";
            string w = ws.get_String_value_Serv(sql, 0, 0);
            double weight_dj = StrToDouble(w);
            //sql = "select coalesce(sum(weight),0) as weight from v_truck_cargo_login_all where lxh='" + tdh +
            //    "' and ioyardid=0 and truckstatus<>'9' and coalesce (cancel_flag,'0')<>'1' and (JFBZ='1' or JFBZ='2')";
            //string w = ws.get_String_value_Serv(sql, 0, 0);
            //double weight_dj = StrToDouble(w);
            //sql = "select coalesce(sum(weight),0) from v_jlb_tdh where tdh='" + tdh + "'";
            //w = ws.get_String_value_Serv(sql, 0, 0);
            //double weight_db = StrToDouble(w);
            if (car_weight > weight_jh - weight_dj)
            {
                MessageBox.Show("车辆计划吨数超出流向计划余数或地磅称重余数！");
                return false;
            }
            return true;
        }

        string wlw_yard = string.Empty;
        //string wlw_pieces = string.Empty;
        //string wlw_weight = string.Empty;
        string wlw_setowner = string.Empty;

        bool isImport = false;

        private void ImportWlwData(DataRow row)
        {
            if (row["cancel_flag"].ToString() == "1")
            {
                MessageBox.Show("提货单已经作废，不能登记！");
                return;
            }
            //if (row["weigh_flag"].ToString() != "0")
            //{
            //    MessageBox.Show("物流网提货单车辆状态不正确，不能登记！");
            //    return;
            //}
            //判断物流网录入的车号和卡号是否合法
            string sql = "select * from RFID_READ where XLH='" + row["RFID_NO"].ToString().Replace(" ", "") + "'and CHEHAO='" + row["CARNO"].ToString().Replace(" ", "") + "' and cardstate='0' and BS is null";
            DataSet dsRFID = ws.getDataSet_Serv(sql);
            if (dsRFID.Tables[0].Rows.Count <= 0)
            {
                MessageBox.Show("RFID卡号非法，不能登记！");
                return;
            }
            //判断市提流向
            if (!CheckCargoTHJH(row["TDH"].ToString(), row["CAR_WEIGHT"].ToString()))
            {
                return;
            }

            isImport = true;
            try
            {
                string carno = row["CARNO"].ToString().Replace(" ", "");
                string name = row["DRIVER_NAME"].ToString();
                string identity = row["DRIVER_IDCARD"].ToString();
                string tel = row["DRIVER_TEL"].ToString();
                string stackname = row["STACKNAME"].ToString();
                string cargoname = row["CARGONAME"].ToString();
                string cargono = row["CARGONO"].ToString();
                string shippername = row["SHIPPER_NAME"].ToString();
                string yard = row["CARGO_PLACE"].ToString();
                string pieces = row["CAR_PIECES"].ToString();
                string weight = row["CAR_WEIGHT"].ToString();
                string shipname = row["SHIPNAME"].ToString();
                string setowner = row["SETOWNER"].ToString();
                string billno = row["BILLNO"].ToString();
                string cardno = row["RFID_NO"].ToString().Replace(" ", "");
                string getowner = row["GETOWNER"].ToString();
                string package = row["PACK"].ToString();
                string shipno = row["SHIPNO"].ToString();
                string barcode = row["BAR_CODE"].ToString();
                string lxh = row["TDH"].ToString();
                string station = row["STATION"].ToString();

                //下拉选择的，如果下拉选项里没有则直接赋给Text
                SetComboBoxValue(comboBox_owner, shippername);
                //this.comboBox_owner.SelectedValue = shippername;
                //if (this.comboBox_owner.SelectedValue == null)
                //    this.comboBox_owner.Text = shippername;
                SetComboBoxValue(comboBoxLXH, lxh);
                //this.comboBoxLXH.SelectedValue = lxh;
                //if (this.comboBoxLXH.SelectedValue == null)
                //    this.comboBoxLXH.Text = lxh;
                SetComboBoxValue(comboBox_shipname, shipname);
                //this.comboBox_shipname.SelectedValue = shipname;
                //if (this.comboBox_shipname.SelectedValue == null)
                //    this.comboBox_shipname.Text = shipname;
                SetComboBoxValue(comboBox_cargoName, cargoname);
                //this.comboBox_cargoName.SelectedValue = cargoname;
                //if (this.comboBox_cargoName.SelectedValue == null)
                //    this.comboBox_cargoName.Text = cargoname;

                this.textBox_carNO.Text = carno;
                this.textBox_cardNO.Text = cardno;
                this.textBox_name.Text = name;
                this.textBox_identity.Text = identity;
                this.textBox_stackName.Text = stackname;
                this.textBox_phone.Text = tel;
                this.textBox_cargoNo.Text = cargono;
                this.textBox_billNO.Text = billno;
                this.textBoxPackage.Text = package;
                this.txtBar_Code.Text = barcode;
                this.textBox_hc.Text = shipno;
                this.textBoxStation.Text = station;
                this.txtWeight.Text = weight;
                this.txtPieces.Text = pieces;

                this.cbJFBZ.SelectedValue = 2;
                this.txtDJ.Text = f_DJ.ToString();
                this.txtJE.Text = "0";

                getowner_global = getowner;
                shipno_global = shipno;

                wlw_yard = yard;
                //wlw_pieces = pieces;
                //wlw_weight = weight;
                wlw_setowner = setowner;
            }
            finally
            {
                isImport = false;
            }
        }
        #endregion

        //the key press event handler for replacing the tab with Enter key
        #region===========press event handler===========
        private void textBox_cardNO_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.comboBox_owner.Focus();
            }
        }

        private void textBox_carNO_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.comboBox_owner.Focus();
            }
        }

        private void txtBar_Code_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.comboBox_owner.Focus();
            }
        }

        private void textBox_billNO_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.comboBox_cargoName.Focus();
            }
        }
        #endregion


        string ckingno_global = "";
        string getowner_global = "";
        //string package_global = "";
        string shipno_global = "";

        private void comboBox_shipname_DropDownClosed(object sender, EventArgs e)
        {
            ShipNameChanged();
        }

        private void comboBox_shipname_SelectedIndexChanged(object sender, EventArgs e)
        {
            //this.textBox_billNO.Focus();

            //string shipname = this.comboBox_shipname.Text.ToString();
            //int index1 = shipname.LastIndexOf("/");
            //if (index1 > 0)
            //{
            //    shipname = shipname.Substring(0,index1);
            //    int index2 = shipname.LastIndexOf("/");
            //    shipname = shipname.Substring(index2+1);
            //    this.textBox_hc.Text = shipname;
            //}
            ShipNameChanged();
        }

        private void ShipNameChanged()
        {
            if (this.comboBox_shipname.SelectedIndex >= 0 && !bLXHisChanged)
            {
                ListItem selectedItem = (ListItem)this.comboBox_shipname.SelectedItem;
                this.textBox_billNO.Text = selectedItem.BillNO;
                //string cargo_name = selectedItem.CargoName;
                SetComboBoxValue(comboBox_cargoName, selectedItem.CargoName);
                //this.comboBox_cargoName.SelectedValue = selectedItem.CargoName;
                this.textBox_cargoNo.Text = selectedItem.CargonNO;
                this.textBox_stackName.Text = selectedItem.StackName;
                //this.textBox_comment.Focus();
                ckingno_global = selectedItem.CkindNO;
                getowner_global = selectedItem.GetOwner;
                this.textBoxPackage.Text = selectedItem.Package;
                shipno_global = selectedItem.ShipNO;
            }
        }

        bool bLXHisChanged = false;

        private void comboBoxLXH_SelectedIndexChanged(object sender, EventArgs e)
        {
            LXHChanged();
        }

        private void comboBoxLXH_DropDownClosed(object sender, EventArgs e)
        {
            LXHChanged();//下拉
        }

        private void LXHChanged()
        {
            if (this.comboBoxLXH.SelectedIndex >= 0)
            {
                ListItem_LX selectedItem = (ListItem_LX)this.comboBoxLXH.SelectedItem;
                this.textBox_billNO.Text = selectedItem.BILLNO;
                SetComboBoxValue(comboBox_cargoName, selectedItem.CARGONAME);
                //this.comboBox_cargoName.SelectedValue = selectedItem.CARGONAME;
                this.textBox_cargoNo.Text = selectedItem.CARGONO;
                this.textBox_stackName.Text = selectedItem.STACKNAME;
                try
                {
                    bLXHisChanged = true;
                    SetComboBoxValue(comboBox_shipname, selectedItem.SHIPNAME);
                    //this.comboBox_shipname.SelectedValue = selectedItem.SHIPNAME;
                    //if (comboBox_shipname.SelectedValue == null)
                    //    this.comboBox_shipname.Text = selectedItem.SHIPNAME;
                }
                finally
                {
                    bLXHisChanged = false;
                }
                //public string SHIPPER_NAME { get; set; }
                //this.textBox_comment.Focus();
                getowner_global = selectedItem.GETOWNER;
                shipno_global = selectedItem.SHIPNO;
                this.textBox_hc.Text = selectedItem.SHIPNO;
            }
        }

        private void comboBox_cargoName_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.textBox_comment.Focus();
        }

        private void comboBox_shipname_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (e.KeyChar == (char)13)
            //{
            //    //this.textBox_billNO.Focus();
            //    this.textBox_yard.Focus();
            //}
        }

        private void comboBox_owner_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.comboBoxLXH.Focus();
            }
        }

        private void comboBox_cargoName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.textBox_comment.Focus();
            }
        }
        private void textBox_yard_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.textBox_comment.Focus();
            }
        }

        //Set the shortcut for all things,such as buttons.
        private void STCHDJ_KeyDown(object sender, KeyEventArgs e)
        {
            //Show or hide car no input window
            if (e.KeyCode == Keys.D0 && e.Control)
            {
                //Show or hide the car no input little window
                if (this.groupBox3.Visible == false)
                {
                    this.btn_car.PerformClick();//perform the click action of btn_car 
                }
                else
                {
                    this.groupBox3.Visible = false;
                }
            }
            if (e.KeyCode == Keys.NumPad0 && e.Control)
            {
                //Show or hide the car no input little window
                if (this.groupBox3.Visible == false)
                {
                    this.btn_car.PerformClick();//perform the click action of btn_car 
                }
                else
                {
                    this.groupBox3.Visible = false;
                }
            }
            if (e.KeyCode == Keys.F1)
            {
                //Show or hide the car no input little window
                if (this.groupBox3.Visible == false)
                {
                    this.btn_car.PerformClick();//perform the click action of btn_car 
                }
                else
                {
                    this.groupBox3.Visible = false;
                }
            }

            //Esc for exixt button
            if (e.KeyCode == Keys.Escape)
            {
                this.button_exist.PerformClick();
            }
            //F3 for clear button
            if (e.KeyCode == Keys.F3)
            {
                this.button_clear.PerformClick();
            }
            //F4 for multiple button
            if (e.KeyCode == Keys.F5)
            {
                this.button_multiple.PerformClick();
            }
            //F5 for save button
            if (e.KeyCode == Keys.F6)
            {
                this.button_save.PerformClick();
            }
        }

        private void button_new_card_Click(object sender, EventArgs e)
        {
            FK frm1 = new FK();
            frm1.Left = 600;
            frm1.Top = 300;
            frm1.Text = "新发卡-" + Session.Operator_User.ToString();
            frm1.Show();
        }

        private void load_data()
        {
            string sql = "select logintime as 登记时间,CARDTIME as 确认时间,lxh as 流向号,SHIPNAME as 船名,BILL_NO as 提单号,cargoname as 货名,truckno as  车号,qdcardnum as 卡号," +
                "DECODE(CANCEL_FLAG,1,'作废',DECODE(to_number(TRUCKSTATUS),0,'登记',1,'发指令',2,'确认',3,'已进门',4,'已理货',5,'已出门')) as 状态,weight as 吨数,pieces as 件数,DRIVERPHONE as 电话,cardadd as 登记地点," +
                "IOYARDID,TRUCKSTATUS,CANCEL_FLAG,ID,DYBZ,YARD AS 地点,ZYJX AS 机械,PACKAGE as 包装,REMARK as 备注,DECODE(LYBZ, '1','物流网导入','停车场登记') as 数据来源,BAR_CODE as 条码号,STATION as 去向," +
                "decode(ISAUTO,'1','是','否') as 自动放车,decode(JFBZ,'0','未收','1','已收','2','不收') as 计费标志,DJ AS 单价,JE as 金额," +
                "decode(TFBZ,'1','是','否') 是否退费,TFSJ 退费时间,TFJE 退费金额 from TRUCK_CARGO_LOGIN" +
                " where (TRUCKSTATUS='0' or TRUCKSTATUS='1' or (TRUCKSTATUS='2' and CARDTIME>=SYSDATE-1.5)) and ioyardid=0  and cardadd='" + card_add + "'" + CycleFilter() + " order by CANCEL_FLAG,TRUCKSTATUS,logintime desc";
            DataSet ds = ws.getDataSet_Serv(sql);
            string sql_un = "select count(*) as un_check from TRUCK_CARGO_LOGIN where coalesce(CANCEL_FLAG,'0')<>'1' and TRUCKSTATUS='1' and IOYARDID='0'and cardadd='" + card_add + "'" + CycleFilter();
            DataSet ds_uncheck = ws.getDataSet_Serv(sql_un);
            if (this.InvokeRequired)
            {
                this.dataGridView1.BeginInvoke(TruckLogin, ds.Tables[0]);
                this.label_cars.BeginInvoke(UncheckRefresh, ds_uncheck.Tables[0]);
            }
            else
            {
                Add_DataTable(ds.Tables[0]);
                fresh_uncheck(ds_uncheck.Tables[0]);
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow DGVRow in this.dataGridView1.Rows)
            {
                if (DGVRow != null)
                {
                    if (DGVRow.Cells["CANCEL_FLAG"].Value.ToString() == "1")
                    {
                        DGVRow.DefaultCellStyle.BackColor = Color.Gray;
                        DGVRow.DefaultCellStyle.SelectionForeColor = Color.Gray;
                        continue;
                    }
                    switch (DGVRow.Cells["TRUCKSTATUS"].Value as string)
                    {
                        case "1":
                            DGVRow.DefaultCellStyle.BackColor = Color.Green;
                            DGVRow.DefaultCellStyle.SelectionForeColor = Color.DarkGreen;
                            break;
                        case "2":
                            DGVRow.DefaultCellStyle.BackColor = Color.Fuchsia;
                            DGVRow.DefaultCellStyle.SelectionForeColor = Color.Fuchsia;
                            break;
                        case "3":
                            DGVRow.DefaultCellStyle.BackColor = Color.Orange;
                            DGVRow.DefaultCellStyle.SelectionForeColor = Color.Orange;
                            break;
                        case "4":
                            DGVRow.DefaultCellStyle.BackColor = Color.LightSkyBlue;
                            DGVRow.DefaultCellStyle.SelectionForeColor = Color.LightSkyBlue;
                            break;
                        case "5":
                            DGVRow.DefaultCellStyle.BackColor = Color.Yellow;
                            DGVRow.DefaultCellStyle.SelectionForeColor = Color.Yellow;
                            break;
                    }
                }
            }
        }

        private void button_refresh_Click(object sender, EventArgs e)
        {
            load_data();
            //carssx();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                string id = this.dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString();
                string sql = "select QDCARDNUM,TRUCKNO,SHIPPER_NAME,SHIPNAME,VOYAGE,BILL_NO,CARGONAME,CARGONO,STACKNAME,YARD,REMARK,DRIVERNAME,DRIVERID,DRIVERPHONE,PACKAGE,LXH,BAR_CODE,LYBZ,STATION from TRUCK_CARGO_LOGIN where ID='" + id + "'";
                DataSet ds = ws.getDataSet_Serv(sql);
                DataTable dt = ds.Tables[0];

                string owner = dt.Rows[0]["SHIPPER_NAME"].ToString();
                string ship_name = dt.Rows[0]["SHIPNAME"].ToString();
                string voyage = dt.Rows[0]["VOYAGE"].ToString();
                string bill_no = dt.Rows[0]["BILL_NO"].ToString();
                string cargo_no = dt.Rows[0]["CARGONO"].ToString();
                string cargoname = dt.Rows[0]["CARGONAME"].ToString();
                string stack_name = dt.Rows[0]["STACKNAME"].ToString();
                string package = dt.Rows[0]["PACKAGE"].ToString();
                string remark = dt.Rows[0]["REMARK"].ToString();
                //string barcode = dt.Rows[0]["BAR_CODE"].ToString();
                string lxh = dt.Rows[0]["LXH"].ToString();
                string lybz = dt.Rows[0]["LYBZ"].ToString();
                string station = dt.Rows[0]["STATION"].ToString();

                SetComboBoxValue(comboBox_owner, owner);
                //this.comboBox_owner.SelectedValue = owner;
                //if (this.comboBox_owner.SelectedValue == null)
                //    this.comboBox_owner.Text = owner;
                SetComboBoxValue(comboBoxLXH, lxh);
                //this.comboBoxLXH.SelectedValue = lxh;
                //if (this.comboBoxLXH.SelectedValue == null)
                //    this.comboBoxLXH.Text = lxh;
                SetComboBoxValue(comboBox_shipname, ship_name);
                //this.comboBox_shipname.SelectedValue = ship_name;
                //if (this.comboBox_shipname.SelectedValue == null)
                //    this.comboBox_shipname.Text = ship_name;
                SetComboBoxValue(comboBox_cargoName, cargoname);
                //this.comboBox_cargoName.SelectedValue = cargoname;
                //if (this.comboBox_cargoName.SelectedValue == null)
                //    this.comboBox_cargoName.Text = cargoname;

                this.textBox_hc.Text = voyage;
                this.textBox_billNO.Text = bill_no;
                this.textBox_cargoNo.Text = cargo_no;
                this.textBox_stackName.Text = stack_name;
                this.textBoxPackage.Text = package;
                this.textBox_comment.Text = remark;
                //this.txtBar_Code.Text = barcode;
                this.textBoxStation.Text = station;

                this.ckbWLWDR.Checked = (lybz == "1");
                this.textBox_cardNO.Focus();


                //this.textBox_hc.Text = voyage_1;
                //this.textBox_billNO.Text = bill_no_1;
                //this.textBox_yard.Text = yard_1;
                //this.textBox_comment.Text = remark_1;
                ////this.comboBox_owner.Text = owner_1;

                //this.comboBox_owner.SelectedText = owner_1;

                //if (owner_is_selected)
                //{
                //    this.comboBox_owner.SelectedIndex = owner_index;
                //}
                //else
                //{
                //    this.comboBox_owner.Text = owner_1;
                //}


                ////this.comboBox_shipname.SelectedValue = shipname_1;
                //this.comboBox_shipname.SelectedIndex = 0;
                //if (shipname_is_selected)
                //{
                //    this.comboBox_shipname.SelectedIndex = shipname_index;
                //}
                //else
                //{
                //    this.comboBox_shipname.Text = shipname_1;
                //}

                ////this.comboBox_cargoName.SelectedValue = cargoname_1;
                //this.textBox_cargoNo.Text = cargono_1;
                //this.textBox_stackName.Text = stackname_1;

                //this.textBox_cardNO.Focus();
            }
            else
            {
                MessageBox.Show("请选中复制行");
            }
        }

        private void SetComboBoxValue(UCComboBox com, string value)
        {
            com.SelectedText = "";//先置空
            com.SelectedValue = value;
            if (com.SelectedValue == null)
                com.Text = value;
        }

        private void textBox_comment_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.textBoxStation.Focus();
            }
        }

        private void textBoxStation_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.textBox_name.Focus();
            }
        }

        private void textBox_name_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.textBox_phone.Focus();
            }
        }

        private void textBox_phone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.textBox_identity.Focus();
            }
        }

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)//判读是否是鼠标右键
            {
                //this.dataGridView1.ClearSelection();
                //this.dataGridView1.Rows[e.RowIndex].Selected = true;
                //this.sendCarToolStripMenuItem.Visible = true;
                //this.sendCarToolStripMenuItem.Visible = true;
                contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);//contextMenuStrip1为菜单控件
            }
        }

        //进车确认
        private void sendCarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
            {
                string status = this.dataGridView1.SelectedRows[i].Cells["状态"].Value.ToString();
                if (status == "发指令")
                {
                    //放车
                    string car_no = this.dataGridView1.SelectedRows[i].Cells["车号"].Value.ToString();
                    string login_time = this.dataGridView1.SelectedRows[i].Cells["登记时间"].Value.ToString();
                    string strSJLY = this.dataGridView1.SelectedRows[i].Cells["数据来源"].Value.ToString();
                    string barcode = this.dataGridView1.SelectedRows[i].Cells["条码号"].Value.ToString();
                    string op_user = Session.Operator_User.ToString();
                    if (!CheckWlwTHDStutas(login_time, car_no))
                        return;
                    String update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=2,CARDTIME=sysdate where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS<>'9' and coalesce(CANCEL_FLAG,'0')<>'1'";
                    string new_id = create_id();
                    string insert_sql = "insert into TRUCK_LOG(ID,TRUCKNO,OPERATENAME,XGSJ,XGNR) values(" + new_id +
                        ",'" + car_no + "','" + op_user + "',sysdate,'停车场放车确认')";
                    int ret1 = ws.execute_UID_Serv(update_sql);
                    int ret2 = ws.execute_UID_Serv(insert_sql);
                    //更新物流网提货单状态
                    if (ret1 > 0 && strSJLY == "物流网导入" && !string.IsNullOrEmpty(barcode))
                    {
                        string update_wlw_sql = "insert into TRUCK_WEIGH_FLAG(TRUCKNO,BAR_CODE,WEIGH_FLAG,CZSJ) values('" + car_no + "','" + barcode + "','5',sysdate)";
                        int ret3 = ws.execute_UID_Serv(update_wlw_sql);
                    }
                    //打印小票
                    string strid = this.dataGridView1.SelectedRows[i].Cells["id"].Value.ToString();
                    string strDYBZ = this.dataGridView1.SelectedRows[i].Cells["DYBZ"].Value.ToString();
                    if (strDYBZ.Equals("0") && strSJLY == "停车场登记")
                    {
                        PrintCode pc = new PrintCode();
                        pc.Run(strid, "大港公司市提车辆登记小票");
                    }

                    if (strSJLY == "物流网导入")
                    {
                        String update_sql1 = "update dg_car_thjh set weigh_flag=5 where BAR_CODE='" + barcode + "'";
                        int retUpdate = ws.execute_UID_Serv(update_sql1);
                        //******************************************************//
                        //顺便调用电商平台的webservice，更新电商平台的车辆状态。//
                        //******************************************************//

                        HttpReValue rv = HttpClass.PostWebApiResult<HttpReValue>(wawrdout + string.Format("?bar_code={0}&car_state={1}", barcode, 5));

                        if (rv.type != "success")
                        {
                            MessageBox.Show(rv.content);
                            //return;
                        }
                        
                    }
                }
            }
            load_data();
        }

        private bool CheckWlwTHDStutas(string login_time, string car_no)
        {
            string sql = "select bar_code,lybz from TRUCK_CARGO_LOGIN where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS<>'9'";
            DataSet ds = ws.getDataSet_Serv(sql);//多票的情况，多票数据需统一判断
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                if (row["lybz"].ToString() == "1")
                {
                    sql = "SELECT cancel_flag,coalesce(weigh_flag, '0') as weigh_flag FROM DG_CAR_THJH WHERE BAR_CODE = '" + row["bar_code"].ToString() + "' ORDER BY PLANDATE DESC";
                    DataSet dsWLW = ws.getDataSet_Serv(sql);
                    if (dsWLW.Tables[0].Rows.Count <= 0 || dsWLW.Tables[0].Rows[0]["cancel_flag"].ToString() == "1")
                    {
                        MessageBox.Show("车辆【" + car_no + "】物流网提货单已作废，不能放车！");
                        return false;
                    }
                    //string flag = dsWLW.Tables[0].Rows[0]["weigh_flag"].ToString();
                    //if (flag != "4" && flag != "5")
                    //{
                    //    MessageBox.Show("车辆【" + car_no + "】物流网提货单状态不正确，不能放车！");
                    //    return false;
                    //}
                }
            }
            return true;
        }

        private void printXPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintXP();
        }

        private void printQYDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintQYD();
        }

        //取消确认
        private void cancelCarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
            {
                string status = this.dataGridView1.SelectedRows[i].Cells["状态"].Value.ToString();
                if (status == "确认")
                {
                    string car_no = this.dataGridView1.SelectedRows[i].Cells["车号"].Value.ToString();
                    string login_time = this.dataGridView1.SelectedRows[i].Cells["登记时间"].Value.ToString();
                    string strSJLY = this.dataGridView1.SelectedRows[i].Cells["数据来源"].Value.ToString();
                    string barcode = this.dataGridView1.SelectedRows[i].Cells["条码号"].Value.ToString();
                    string op_user = Session.Operator_User.ToString();
                    String update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=1 where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS<>'9' and coalesce(CANCEL_FLAG,'0')<>'1'";
                    string new_id = create_id();
                    string insert_sql = "insert into TRUCK_LOG(ID,TRUCKNO,OPERATENAME,XGSJ,XGNR) values(" + new_id +
                        ",'" + car_no + "','" + op_user + "',sysdate,'停车场取消放车')";
                    int ret1 = ws.execute_UID_Serv(update_sql);
                    int ret2 = ws.execute_UID_Serv(insert_sql);
                    ////更新物流网提货单状态
                    if (ret1 > 0 && strSJLY == "物流网导入" && !string.IsNullOrEmpty(barcode))
                    {
                        string update_wlw_sql = "insert into TRUCK_WEIGH_FLAG(TRUCKNO,BAR_CODE,WEIGH_FLAG,CZSJ) values('" + car_no + "','" + barcode + "','4',sysdate)";
                        int ret4 = ws.execute_UID_Serv(update_wlw_sql);
                    }
                    //删除停车计费
                    string deleteFS_sql = "delete from Truck_FS where TRUCKNO = '" + car_no + "' and LOGINTIME = to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss')";
                    int ret3 = ws.execute_UID_Serv(deleteFS_sql);
                }
            }
            load_data();
        }

        //登记修改
        private void changeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                string id = this.dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString();
                string sql = "select QDCARDNUM,TRUCKNO,SHIPPER_NAME,SHIPNAME,VOYAGE,BILL_NO,CARGONAME,CARGONO,STACKNAME,YARD,REMARK,DRIVERNAME,DRIVERID,DRIVERPHONE,PACKAGE,LXH,BAR_CODE,LYBZ,STATION from TRUCK_CARGO_LOGIN where ID='" + id + "'";
                DataSet ds = ws.getDataSet_Serv(sql);
                DataTable dt = ds.Tables[0];
                string card_no = dt.Rows[0]["QDCARDNUM"].ToString();
                string truck_no = dt.Rows[0]["TRUCKNO"].ToString();
                string owner = dt.Rows[0]["SHIPPER_NAME"].ToString();
                string ship_name = dt.Rows[0]["SHIPNAME"].ToString();
                string voyage = dt.Rows[0]["VOYAGE"].ToString();
                string bill_no = dt.Rows[0]["BILL_NO"].ToString();
                string cargo_name = dt.Rows[0]["CARGONAME"].ToString();
                string cargo_no = dt.Rows[0]["CARGONO"].ToString();
                string stack_name = dt.Rows[0]["STACKNAME"].ToString();
                string package = dt.Rows[0]["PACKAGE"].ToString();
                string remark = dt.Rows[0]["REMARK"].ToString();
                string driver_name = dt.Rows[0]["DRIVERNAME"].ToString();
                string driver_id = dt.Rows[0]["DRIVERID"].ToString();
                string driver_phone = dt.Rows[0]["DRIVERPHONE"].ToString();

                string lxh = dt.Rows[0]["LXH"].ToString();
                string barcode = dt.Rows[0]["BAR_CODE"].ToString();
                string lybz = dt.Rows[0]["LYBZ"].ToString();
                string station = dt.Rows[0]["STATION"].ToString();

                this.textBox_cardNO.Text = card_no;
                this.textBox_carNO.Text = truck_no;
                this.comboBox_owner.SelectedValue = owner;
                this.comboBox_shipname.SelectedValue = ship_name;
                this.comboBoxLXH.SelectedValue = lxh;
                this.textBox_hc.Text = voyage;
                this.textBox_billNO.Text = bill_no;
                this.comboBox_cargoName.SelectedValue = cargo_name;
                this.textBox_cargoNo.Text = cargo_no;
                this.textBox_stackName.Text = stack_name;
                this.textBoxPackage.Text = package;
                this.textBox_comment.Text = remark;
                this.textBox_name.Text = driver_name;
                this.textBox_identity.Text = driver_id;
                this.textBox_phone.Text = driver_phone;
                this.txtBar_Code.Text = barcode;
                this.ckbWLWDR.Checked = (lybz == "1");
                this.textBoxStation.Text = station;

                //this.comboBox_owner.SelectedValue = owner;
                is_update = true;
                update_id = id;
            }
        }
        string Str_ID = "";
        string Str_bj = "";
        string Str_DYBZ = "";
        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                DataGridViewRow dataGridViewRow1 = dataGridView1.Rows[e.RowIndex];
                //dataGridView1.ClearSelection();
                //dataGridViewRow1.Selected = true;
                Str_ID = dataGridViewRow1.Cells["id"].Value.ToString();
                Str_bj = dataGridViewRow1.Cells["TRUCKSTATUS"].Value.ToString();
                Str_DYBZ = dataGridViewRow1.Cells["DYBZ"].Value.ToString();
            }
        }

        /// <summary>
        /// 打印小票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            //if (Str_bj.Equals("2") && Str_DYBZ.Equals("0"))
            //{
            //PrinForm pf = new PrinForm(Str_ID, "大港公司市提车辆登记小票");
            //pf.Show();
            //}
            //else
            //{
            //    MessageBox.Show(Str_bj + "不能打印小票");
            //}
            PrintXP();
        }

        /// <summary>
        /// 打印小票
        /// </summary>
        private void PrintXP()
        {
            foreach (DataGridViewRow dgvr in this.dataGridView1.SelectedRows)
            {
                string strid = dgvr.Cells["id"].Value.ToString();
                string strbj = dgvr.Cells["TRUCKSTATUS"].Value.ToString();
                string strDYBZ = dgvr.Cells["DYBZ"].Value.ToString();
                if (strbj.Equals("2") && strDYBZ.Equals("0"))
                {
                    string strSJLY = dgvr.Cells["数据来源"].Value.ToString();
                    if (strSJLY == "物流网导入")
                    {
                        MessageBox.Show("物流网导入的车辆，请打印汽运单！");
                        continue;
                    }
                    PrintCode pc = new PrintCode();
                    pc.Run(strid, "大港公司市提车辆登记小票");
                }
            }
        }

        /// <summary>
        /// 打印汽运单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDYQYD_Click(object sender, EventArgs e)
        {
            PrintQYD();
        }

        /// <summary>
        /// 打印汽运单
        /// </summary>
        private void PrintQYD()
        {
            if (this.dataGridView1.SelectedRows != null && this.dataGridView1.SelectedRows.Count > 0)
            {
                if (this.dataGridView1.SelectedRows.Count > 1)
                {
                    MessageBox.Show("打印汽运单不能多选！");
                    return;
                }
                DataGridViewRow dgvr = this.dataGridView1.SelectedRows[0];
                string strbj = dgvr.Cells["TRUCKSTATUS"].Value.ToString();
                if (strbj.Equals("2"))
                {
                    string strSJLY = dgvr.Cells["数据来源"].Value.ToString();
                    if (strSJLY == "停车场登记")
                    {
                        MessageBox.Show("停车场登记的车辆，请打印小票！");
                        return;
                    }
                    string strid = dgvr.Cells["id"].Value.ToString();
                    PrintCode pc = new PrintCode();
                    pc.Run_QYD(strid);
                }
            }
        }

        #region 计算停车费用
        /// <summary>
        /// 显示停车费用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            //CalcFS(login_time, ws.GetSysDateTime().ToString(), car_no);//计算停车费用
            if (dataGridView1.SelectedRows != null && dataGridView1.SelectedRows.Count > 0)
            {
                DataGridViewRow row = dataGridView1.SelectedRows[0];
                string status = row.Cells["状态"].Value.ToString();
                if (status == "确认")
                {
                    string carNo = row.Cells["车号"].Value.ToString();
                    string loginTime = row.Cells["登记时间"].Value.ToString();
                    string commandTime = row.Cells["确认时间"].Value.ToString();

                    string sql = "select TBYBS, TBBBS, YBSF, BBSF, HJ from TRUCK_FS where TRUCKNO = '" + carNo +
                        "' and LOGINTIME = to_date('" + loginTime + "','yyyy-mm-dd hh24:mi:ss') and COMMANDTIME = to_date('" + commandTime + "','yyyy-mm-dd hh24:mi:ss')";
                    DataTable dt = ws.getDataSet_Serv(sql).Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        DataRow rowFS = dt.Rows[0];
                        ShowTJSF(rowFS["TBBBS"].ToString(), rowFS["TBYBS"].ToString(), rowFS["BBSF"].ToString(), rowFS["YBSF"].ToString(), rowFS["HJ"].ToString());
                    }
                    else
                    {
                        int iDays = 0, iNights = 0;
                        double ybsf = 0, bbsf = 0, hj = 0;
                        CalcFS(loginTime, commandTime, carNo, ref iDays, ref iNights, ref ybsf, ref bbsf, ref hj);
                        ShowTJSF(iDays.ToString(), iNights.ToString(), bbsf.ToString(), ybsf.ToString(), hj.ToString());
                    }
                    pnlTCJF.Visible = true;
                }
                else
                {
                    pnlTCJF.Visible = false;
                }
            }
            else
            {
                pnlTCJF.Visible = false;
            }
        }

        /// <summary>
        /// 显示停车计费
        /// </summary>
        /// <param name="days"></param>
        /// <param name="nights"></param>
        /// <param name="bbsf"></param>
        /// <param name="ybsf"></param>
        /// <param name="hj"></param>
        private void ShowTJSF(string days, string nights, string bbsf, string ybsf, string hj)
        {
            pnlTCJF.Visible = true;
            lblDays.Text = days;
            lblNights.Text = nights;
            lblBBSF.Text = bbsf;
            lblYBSF.Text = ybsf;
            lblHJ.Text = hj;
        }

        const double JFBZ_DAY = 20, JFBZ_NIGHT = 30;//计费标准，白班20， 夜班30

        /// <summary>
        /// 计算停车费用
        /// </summary>
        private void CalcFS(string loginTime, string commandTime, string truckNo, ref int iDays, ref int iNights, ref double ybsf, ref double bbsf, ref double hj)
        {
            DateTime beginTime = DateTime.Parse(loginTime),
                endTime = DateTime.Parse(commandTime),
                eightTime = DateTime.Parse(beginTime.ToString("yyyy-MM-dd 8:00:00")),//早上8点
                eighteenTime = DateTime.Parse(beginTime.ToString("yyyy-MM-dd 18:00:00"));//晚上18点

            double tbsj = endTime.Subtract(beginTime).TotalHours;
            iDays = 0;
            iNights = 0;

            if (beginTime < eightTime)//早8点之前
            {
                iNights++;
                CalcTBSJ(eightTime, endTime, true, ref iDays, ref iNights);
            }
            else if (beginTime < eighteenTime)//早8点到晚16点之间
            {
                iDays++;
                CalcTBSJ(eighteenTime, endTime, false, ref iDays, ref iNights);
            }
            else//晚18点之后
            {
                iNights++;
                eightTime = eightTime.AddDays(1);//第二天早8点
                CalcTBSJ(eightTime, endTime, true, ref iDays, ref iNights);
            }

            ybsf = iNights * JFBZ_NIGHT;
            bbsf = iDays * JFBZ_DAY;
            hj = ybsf + bbsf;

            string id = create_id();
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("INSERT INTO TRUCK_FS(ID, TRUCKNO, LOGINTIME, COMMANDTIME, TBSJ, TBYBS, TBBBS, YBSF, BBSF, HJ) ");
            sbSql.Append("VALUES(" + id + ",'" + truckNo + "',");
            sbSql.Append("to_date('" + loginTime + "','YYYY-MM-DD HH24:MI:SS'),");
            sbSql.Append("to_date('" + commandTime + "','YYYY-MM-DD HH24:MI:SS'),");
            sbSql.Append(tbsj + "," + iNights + "," + iDays + "," + ybsf + "," + bbsf + " ," + hj + ")");
            int ret1 = ws.execute_UID_Serv(sbSql.ToString());
        }

        /// <summary>
        /// 计算停车班数
        /// </summary>
        /// <param name="time"></param>
        /// <param name="endTime"></param>
        /// <param name="isDay"></param>
        /// <param name="days"></param>
        /// <param name="nights"></param>
        private void CalcTBSJ(DateTime time, DateTime endTime, bool isDay, ref int days, ref int nights)
        {
            if (endTime <= time)
            {
                return;
            }
            else
            {
                if (isDay)
                {
                    days++;
                    DateTime tempTime = DateTime.Parse(time.ToString("yyyy-MM-dd 18:00:00"));
                    CalcTBSJ(tempTime, endTime, false, ref days, ref nights);
                }
                else
                {
                    nights++;
                    DateTime tempTime = DateTime.Parse(time.ToString("yyyy-MM-dd 8:00:00")).AddDays(1);
                    CalcTBSJ(tempTime, endTime, true, ref days, ref nights);
                }
            }
        }
        #endregion

        /// <summary>
        /// 废卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAbandonCard_Click(object sender, EventArgs e)
        {
            using (AbandonCardForm fk = new AbandonCardForm())
            {
                fk.Text = "废卡-" + Session.Operator_User.ToString();
                fk.ShowDialog();
            }
        }

        private void ckbWLWDR_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbWLWDR.Checked)
            {
                txtBar_Code.Focus();
            }
        }

        /// <summary>
        /// 修改货代和货信息，多选时信息批量修改成一样的
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModify_Click(object sender, EventArgs e)
        {
            bool bHasImport = false; //是否有物流网导入数据，若有，需控制部分字段不能为空
            List<string> listIDs = new List<string>();
            foreach (DataGridViewRow dgvr in this.dataGridView1.SelectedRows)
            {
                if (dgvr.Cells["TRUCKSTATUS"].Value.ToString() == "0")//登记
                {
                    listIDs.Add(dgvr.Cells["ID"].Value.ToString());
                    if (!bHasImport && dgvr.Cells["数据来源"].Value.ToString() == "物流网导入")
                    {
                        bHasImport = true;
                    }
                }
            }
            if (listIDs.Count > 0)
            {
                string sql = "select SHIPPER_NAME,SHIPNAME,VOYAGE,BILL_NO,CARGONAME,CARGONO,STACKNAME,REMARK,PACKAGE,LXH,STATION from TRUCK_CARGO_LOGIN where ID='" + listIDs[0] + "'";
                DataTable dt = ws.getDataSet_Serv(sql).Tables[0];
                string owner = dt.Rows[0]["SHIPPER_NAME"].ToString();
                string ship_name = dt.Rows[0]["SHIPNAME"].ToString();
                string voyage = dt.Rows[0]["VOYAGE"].ToString();
                string bill_no = dt.Rows[0]["BILL_NO"].ToString();
                string cargo_no = dt.Rows[0]["CARGONO"].ToString();
                string cargoname = dt.Rows[0]["CARGONAME"].ToString();
                string stack_name = dt.Rows[0]["STACKNAME"].ToString();
                string package = dt.Rows[0]["PACKAGE"].ToString();
                string remark = dt.Rows[0]["REMARK"].ToString();
                string lxh = dt.Rows[0]["LXH"].ToString();
                string station = dt.Rows[0]["STATION"].ToString();

                using (STModifyForm oForm = new STModifyForm(bHasImport, owner, lxh, ship_name, voyage, bill_no, cargoname, cargo_no, stack_name, package, station, remark))
                {
                    if (oForm.ShowDialog() == DialogResult.OK)
                    {
                        string strSQL = "update truck_cargo_login set SHIPPER_NAME='{0}',SHIPNAME='{1}',VOYAGE='{2}',BILL_NO='{3}',CARGONAME='{4}',CARGONO='{5}',STACKNAME='{6}',REMARK='{7}',PACKAGE='{8}',LXH='{9}',STATION='{10}' where id = {11}";
                        foreach (string id in listIDs)
                        {
                            ws.execute_UID_Serv(string.Format(strSQL, oForm.ShipperName, oForm.ShipName, oForm.HC, oForm.BillNo, oForm.CargoName, oForm.CargoNo, oForm.StackName, oForm.Comment, oForm.Pack, oForm.LXH, oForm.Station, id));
                        }
                        MessageBox.Show("修改成功！");
                        load_data();
                    }
                }
            }
            else
            {
                MessageBox.Show("只有状态为登记的车辆信息可以修改！");
            }
        }

        /// <summary>
        /// 拉循环车辆录入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCycle_Click(object sender, EventArgs e)
        {
            CycleCLLRForm oForm = new CycleCLLRForm();
            oForm.Show();
        }

        private void txtBar_Code_TextChanged(object sender, EventArgs e)
        {
            if (this.ckbWLWDR.Checked && !isImport && this.txtBar_Code.Text.Trim().Length >= 8)
            {
                CheckWlwByBarCode();//检测物流网导入
            }
        }

        /// <summary>
        /// 作废，反写到物流网提货计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cancelStateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count <= 0)
                return;
            if (MessageBox.Show("确定要作废选中数据吗？", "系统提示", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                return;

            for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
            {
                string status = this.dataGridView1.SelectedRows[i].Cells["状态"].Value.ToString();
                if (status != "作废")
                {
                    string strSJLY = this.dataGridView1.SelectedRows[i].Cells["数据来源"].Value.ToString();
                    string barcode = this.dataGridView1.SelectedRows[i].Cells["条码号"].Value.ToString();
                    string car_no = this.dataGridView1.SelectedRows[i].Cells["车号"].Value.ToString();
                    if (strSJLY == "物流网导入" && !string.IsNullOrEmpty(barcode))
                    {
                        string sql = "SELECT coalesce(weigh_flag, '0') as weigh_flag FROM DG_CAR_THJH WHERE BAR_CODE = '" + barcode + "' ORDER BY PLANDATE DESC";
                        DataSet dsWLW = ws.getDataSet_Serv(sql);
                        if (dsWLW.Tables[0].Rows.Count > 0)
                        {
                            string strWeigh_Flag = dsWLW.Tables[0].Rows[0]["weigh_flag"].ToString();
                            if (strWeigh_Flag == "1" || strWeigh_Flag == "2" || strWeigh_Flag == "3")
                            {
                                MessageBox.Show("车辆【" + car_no + "】已过磅，不能作废！", "系统提示");
                                return;
                            }
                        }
                    }
                    string strID = this.dataGridView1.SelectedRows[i].Cells["ID"].Value.ToString();
                    string update_sql = "update TRUCK_CARGO_LOGIN set CANCEL_FLAG='1',CANCEL_TIME=sysdate where ID=" + strID;
                    ws.execute_UID_Serv(update_sql);
                    string op_user = Session.Operator_User.ToString();
                    string new_id = create_id();
                    string insert_sql = "insert into TRUCK_LOG(ID,TRUCKNO,OPERATENAME,XGSJ,XGNR) values(" + new_id + ",'" + car_no + "','" + op_user + "',sysdate,'停车场作废')";
                    ws.execute_UID_Serv(insert_sql);
                    //作废物流网提货单
                    if (strSJLY == "物流网导入" && !string.IsNullOrEmpty(barcode))
                    {
                        string delete_wlw_sql = "delete from TRUCK_CANCEL_FLAG where BAR_CODE = '" + barcode + "'";
                        ws.execute_UID_Serv(delete_wlw_sql);
                        string insert_wlw_sql = "INSERT INTO TRUCK_CANCEL_FLAG(TRUCKNO,BAR_CODE,CANCEL_FLAG,CANCEL_TIME) values('" + car_no + "','" + barcode + "','1',sysdate)";
                        ws.execute_UID_Serv(insert_wlw_sql);
                    }
                    if (strSJLY == "物流网导入")
                    {
                        String update_sql1 = "update dg_car_thjh set CANCEL_FLAG=1,CANCEL_TIME=sysdate where BAR_CODE='" + barcode + "'";
                        int ret1 = ws.execute_UID_Serv(update_sql1);
                        //******************************************************//
                        //顺便调用电商平台的webservice，更新电商平台的车辆状态。//
                        //******************************************************//
                        HttpReValue rv = HttpClass.PostWebApiResult<HttpReValue>(wawrdout + string.Format("?bar_code={0}&car_state={1}", barcode, -1));
                        if (rv.type != "success")
                        {
                            MessageBox.Show(rv.content);
                            //return;
                        }
                        
                    }
                   
                }
            }
            load_data();
        }

        /// <summary>
        /// 查看自动放车设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnViewAutoSendCarSet_Click(object sender, EventArgs e)
        {
            using (AutoSendCarForm form = new AutoSendCarForm())
            {
                form.ShowDialog();
            }
        }

        /// <summary>
        /// 退费
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefund_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows != null && this.dataGridView1.SelectedRows.Count > 0)
            {
                if (this.dataGridView1.SelectedRows.Count > 1)
                {
                    MessageBox.Show("只能选择一条数据！");
                    return;
                }
                string strID = this.dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString();
                string sql = "select weight,decode(coalesce(jfbz,'0'),'1','已收','2','不收','未收') jfbz,je,sysdate tfsj from truck_cargo_login where ID='" + strID + "'";
                DataTable dt = ws.getDataSet_Serv(sql).Tables[0];
                double weight = StrToDouble(dt.Rows[0]["weight"].ToString());
                double je = StrToDouble(dt.Rows[0]["je"].ToString());
                string jfbz = dt.Rows[0]["jfbz"].ToString();
                string jfsj = dt.Rows[0]["tfsj"].ToString();
                using (STRefoundForm form = new STRefoundForm(weight, f_DJ, je, jfbz, jfsj))
                {
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        sql = "update truck_cargo_login set tfje='" + form.TFJE + "',tfbz='1',tfsj=sysdate where id=" + strID + "";
                        int i = ws.execute_UID_Serv(sql);
                        if (i > 0)
                        {
                            //记录log
                            //sql = "insert into truck_refund_log values('{0}','{1}','{2}',{3},'{4}',{5},'{6}',sysdate)";
                            //ws.execute_UID_Serv(string.Format(sql, Guid.NewGuid().ToString(), strID, jfbz, je, form.JFBZ, form.JE, Session.Operator_User));
                            MessageBox.Show("退费成功！");
                            load_data();
                        }
                    }
                }
            }
        }
    }
}
